gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 02:59:23 25 4
gpt4 key购买 nike

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

我整天都在互联网上搜索并尝试不同的东西,以了解如何将网页的内容转换为java中的字符串(没有webview)。找到的所有内容要么已被弃用,要么是我缺乏理解阻碍了我,我一直在阅读文档和所有内容,但它只是让我头晕,即使任务似乎很简单,在 php 中它只需要一个函数:file_get_contents()

我可以使用不可见的 WebView 来做到这一点,但据我所知这不是可行的方法,而且我还希望能够将内容发布到网页上(尽管我可以通过在 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");

关于java - Java中以字符串形式获取网页内容(类似于php的file_get_contents()),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42586601/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com