在 Java 中以字符串形式获取网页内容(类似于 php 的 file_get_contents())



首先,我是一个菜鸟,当涉及到android/java时,我本周才开始研究它。

我一直在搜索Internet,并整天尝试不同的内容,以了解如何将网页的内容输入Java中的字符串(无网络视图)。要么要找到的一切都是弃用的,要么是我缺乏理解,我一直在阅读文档,但一切都使我的头旋转了,即使任务似乎很简单,在PHP中,它只是需要一个功能:file_get_contents()

我能够使用隐形网络浏览量进行此操作,但据我所知,这不是要走的路,而且我也希望能够将其发布到网页上(尽管我可能能够通过在WebView上执行一些JavaScript,但这似乎并不是要走的路)。

有人可以给我一个简单的例子,说明如何将网页的内容输入字符串还有一个简单的示例将某些内容发布到网页上(并将响应检索到字符串中)

如果可能的话,请进行一些解释,但是如果我得到一个工作示例,我可以弄清楚它为什么起作用。

对于任何可能遇到此问题的人,我已经使用以下代码解决了它(这包括添加帖子参数,如果需要/需要):

private class GetContents extends AsyncTask<String, Void, String> {
        protected String doInBackground(String... p) {
            String targetURL = p[0];
            String urlParameters = p[1];
        URL url;
        HttpURLConnection connection = null;
        try {
            //Create connection
            url = new URL(targetURL);
            connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("POST");
            connection.setRequestProperty("Content-Type",
                    "application/x-www-form-urlencoded");
            connection.setRequestProperty("Content-Length", "" +
                    Integer.toString(urlParameters.getBytes().length));
            connection.setRequestProperty("Content-Language", "en-US");
            connection.setUseCaches(false);
            connection.setDoInput(true);
            connection.setDoOutput(true);
            //Send request
            DataOutputStream wr = new DataOutputStream(
                    connection.getOutputStream());
            wr.writeBytes(urlParameters);
            wr.flush();
            wr.close();
            //Get Response
            InputStream is = connection.getInputStream();
            BufferedReader rd = new BufferedReader(new InputStreamReader(is));
            String line;
            StringBuffer response = new StringBuffer();
            while ((line = rd.readLine()) != null) {
                response.append(line);
                response.append('r');
            }
            rd.close();
            return response.toString();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {
            if (connection != null) {
                connection.disconnect();
            }
        }

        }
        protected void onPostExecute(String result) {
            // do something
        }
    }

然后使用它,例如:new GetContents.execute(" http://example.com"," a = b");

最新更新