bit*_*its 3 html java httpurlconnection
我从java httpurlconnection获得了一些代码来切断html,而且我几乎是从Java中的网站获取html的代码.除了我无法使此代码使用的一个特定网站:
我想从这个网站获取HTML:
http://www.geni.com/genealogy/people/William-Jefferson-Blythe-Clinton/6000000001961474289
但我一直在抓垃圾角色.虽然它适用于任何其他网站,如http://www.google.com.
这是我正在使用的代码:
public static String PrintHTML(){
URL url = null;
try {
url = new URL("http://www.geni.com/genealogy/people/William-Jefferson-Blythe-Clinton/6000000001961474289");
} catch (MalformedURLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
HttpURLConnection connection = null;
try {
connection = (HttpURLConnection) url.openConnection();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
connection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.2.6) Gecko/20100625 Firefox/3.6.6");
try {
System.out.println(connection.getResponseCode());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String line;
StringBuilder builder = new StringBuilder();
BufferedReader reader = null;
try {
reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
while ((line = reader.readLine()) != null) {
builder.append(line);
builder.append("\n");
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String html = builder.toString();
System.out.println("HTML " + html);
return html;
}
Run Code Online (Sandbox Code Playgroud)
我不明白为什么它不适用于我上面提到的URL.
任何帮助将不胜感激.
无论客户端的功能如何,该站点都会错误地压缩响应.通常,服务器应该只在客户端支持时通过gzip响应(by Accept-Encoding: gzip).你需要使用它来解压缩它GZIPInputStream.
reader = new BufferedReader(new InputStreamReader(new GZIPInputStream(connection.getInputStream()), "UTF-8"));
Run Code Online (Sandbox Code Playgroud)
请注意,我还将正确的字符集添加到InputStreamReader构造函数中.通常,您希望从Content-Type响应的标题中提取它.
有关更多提示,另请参阅如何使用URLConnection来触发和处理HTTP请求?如果你想要的只是从HTML解析/提取信息,那么我强烈建议使用像Jsoup这样的HTML解析器.
| 归档时间: |
|
| 查看次数: |
440 次 |
| 最近记录: |