jjn*_*guy 116 java compression http
我希望能够获取一个网页的html并将其保存到一个String
,所以我可以对它进行一些处理.另外,我如何处理各种类型的压缩.
我将如何使用Java进行此操作?
Bal*_*usC 169
我会使用像Jsoup这样体面的HTML解析器.然后就像这样简单:
String html = Jsoup.connect("http://stackoverflow.com").get().html();
Run Code Online (Sandbox Code Playgroud)
它完全透明地处理GZIP和分块响应以及字符编码.它提供了更多的优势,例如像CSS查询器的HTML 遍历和操作,就像jQuery可以做的那样.你只需抓住它Document
,而不是像String
.
Document document = Jsoup.connect("http://google.com").get();
Run Code Online (Sandbox Code Playgroud)
你真的不希望运行的基本字符串的方法,甚至正则表达式的HTML来处理它.
Bil*_*ard 107
这是使用Java的URL的一些经过测试的代码类.不过,我建议做一个比处理异常或将它们传递给调用堆栈更好的工作.
public static void main(String[] args) {
URL url;
InputStream is = null;
BufferedReader br;
String line;
try {
url = new URL("http://stackoverflow.com/");
is = url.openStream(); // throws an IOException
br = new BufferedReader(new InputStreamReader(is));
while ((line = br.readLine()) != null) {
System.out.println(line);
}
} catch (MalformedURLException mue) {
mue.printStackTrace();
} catch (IOException ioe) {
ioe.printStackTrace();
} finally {
try {
if (is != null) is.close();
} catch (IOException ioe) {
// nothing to see here
}
}
}
Run Code Online (Sandbox Code Playgroud)
jjn*_*guy 24
Bill的答案非常好,但您可能希望对压缩或用户代理等请求做一些事情.以下代码显示了如何对请求进行各种类型的压缩.
URL url = new URL(urlStr);
HttpURLConnection conn = (HttpURLConnection) url.openConnection(); // Cast shouldn't fail
HttpURLConnection.setFollowRedirects(true);
// allow both GZip and Deflate (ZLib) encodings
conn.setRequestProperty("Accept-Encoding", "gzip, deflate");
String encoding = conn.getContentEncoding();
InputStream inStr = null;
// create the appropriate stream wrapper based on
// the encoding type
if (encoding != null && encoding.equalsIgnoreCase("gzip")) {
inStr = new GZIPInputStream(conn.getInputStream());
} else if (encoding != null && encoding.equalsIgnoreCase("deflate")) {
inStr = new InflaterInputStream(conn.getInputStream(),
new Inflater(true));
} else {
inStr = conn.getInputStream();
}
Run Code Online (Sandbox Code Playgroud)
要同时设置user-agent,请添加以下代码:
conn.setRequestProperty ( "User-agent", "my agent name");
Run Code Online (Sandbox Code Playgroud)
Jon*_*eet 12
好吧,你可以使用内置库,如URL和URLConnection,但它们不会给予很多控制.
我个人会选择Apache HTTPClient库.
编辑: Apache已将HTTPClient设置为报废.替换是:HTTP组件
归档时间: |
|
查看次数: |
186528 次 |
最近记录: |