1 完美解决jsoup获取响应内容不完整 (或者内容格式不对)
Jsoup抓取网页只能抓取一部分不能完整获取响应内容时,一般有以下几个原因。
- 网络异常,这个很少发生,jsoup会报告exception
- 网络超时,可以设置 connection.timeout(n) 增加超时时间。
- 看起来都正常,没有异常发生。 但是获取的数据就是少了一截。
如果获取到的数据不超过1024k,程序正常,得到的数据也正常。
一旦数据超过1024k时,数据就只有预期得到数据的前1024k字节了。
仔细查找jsoup的api 发现,默认设置下,jsoup最大获取的响应长度正好时1M。
所以这个时候只要设置 connection.maxBodySize(0),设置为0,就可以得到不限响应长度的数据了。
网上有人这样写说可以解决
Document = Jsoup.connect(url)
.header(“Accept-Encoding”, “gzip, deflate”)
.userAgent(“Mozilla/5.0 (Windows NT 6.1; WOW64; rv:23.0) Gecko/20100101 Firefox/23.0”)
.maxBodySize(0)
.timeout(600000)
.get();
经过测试,这样还是不能解决。
最终发现,下面这样写才能完美解决:
get方法
Response resp = Jsoup.connect(url)
.timeout(60000)
.method(Connection.Method.GET)
.maxBodySize(0)
.followRedirects(false)
.execute();
String htmlStr = new String(resp.bodyAsBytes());
post方法
Response resp =Jsoup.connect(url).ignoreContentType(true)
.method(Connection.Method.POST).header(“Content-Type”,“application/json”)
.requestBody(param)
.execute();
String s = new String(resp.bodyAsBytes());
return s;
}
FAQ
1 org.jsoup.UncheckedIOException: java.io.IOException: Premature EOF
服务内调用了第三方的接口,
Connection.Response response= Jsoup.connect(cloudUrl).ignoreContentType(true).method(Connection.Method.POST)
.header("Content-Type", "application/json;charset=UTF-8").requestBody(param)
.execute();
Map<String, Object> responseMap = JSONObject.parseObject(response.body());
突然没有返回,查看报错如上。
是response.body()
方法报错。
具体报错原因未知,猜测还是返回体太大的原因,用上面的方法String htmlStr = new String(resp.bodyAsBytes())
代替后解决。
2org.jsoup.HttpStatusException: HTTP error fetching URL. Status=503,
org.jsoup.HttpStatusException: HTTP error fetching URL. Status=503, URL=http://192.168.70.10/abxadmin/abx-message/message/actuator/health
at org.jsoup.helper.HttpConnection$Response.execute(HttpConnection.java:776)
at org.jsoup.helper.HttpConnection$Response.execute(HttpConnection.java:722)
at org.jsoup.helper.HttpConnection.execute(HttpConnection.java:306)
at org.jsoup.helper.HttpConnection.get(HttpConnection.java:295)
at cn.com.agree.ab.a5.runtime.controller.CheckHealthyController.main(CheckHealthyController.java:128)
2.1问题
报错如上,访问代码如下,
String text2 = Jsoup.connect(messageUrl)
.ignoreContentType(true)
.method(Connection.Method.GET)
.header("Content-Type","application/json")
.get().body().text();
2.2 解决
修改代码如下
doc = Jsoup.connect(messageUrl)
.ignoreContentType(true)
.method(Connection.Method.GET)
.header("Content-Type","application/json")
.get();
if (doc!=null) {
String text = doc.body().text();
Map resultMap = (Map) JSONObject.parse(text);
String status = (String) resultMap.get("status");
System.out.println(status);
}
2.3 问题分析
略