3 回答
TA贡献1793条经验 获得超6个赞
您可以使用HttpClient执行HTTP GET并检索HTML响应,如下所示:
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet(url);
HttpResponse response = client.execute(request);
String html = "";
InputStream in = response.getEntity().getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
StringBuilder str = new StringBuilder();
String line = null;
while((line = reader.readLine()) != null)
{
str.append(line);
}
in.close();
html = str.toString();
TA贡献1828条经验 获得超6个赞
这个问题有点老了,但是我认为现在已经弃用了,等等DefaultHttpClient,我应该发布我的答案HttpGet。给定URL,此函数应获取并返回HTML。
public static String getHtml(String url) throws IOException {
// Build and set timeout values for the request.
URLConnection connection = (new URL(url)).openConnection();
connection.setConnectTimeout(5000);
connection.setReadTimeout(5000);
connection.connect();
// Read and store the result line by line then return the entire string.
InputStream in = connection.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
StringBuilder html = new StringBuilder();
for (String line; (line = reader.readLine()) != null; ) {
html.append(line);
}
in.close();
return html.toString();
}
- 3 回答
- 0 关注
- 527 浏览
相关问题推荐
添加回答
举报