JSOUP请求返回Json数据

最近在使用 JSOUP  作为 爬虫  爬取数据,在用习惯了 JSOUP  后,因为那种链式结构,非常喜欢,故想用它来请求接口,构造请求头的时候非常方便。其实它必须是支持的,因为底层使用的还是 HttpConnection  做为处理的,代码如下:

Document doc = Jsoup
		.connect(Constant.DATA_URL)
		.header("Accept", "*/*")
		.header("Accept-Encoding", "gzip, deflate")
		.header("Accept-Language","zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3")
		.header("Content-Type", "application/json;charset=UTF-8")
		.header("User-Agent","Mozilla/5.0 (Windows NT 6.1; WOW64; rv:48.0) Gecko/20100101 Firefox/48.0")
		.timeout(10000).get();
Element body = doc.body();
JSONObject json = JSONObject.fromObject(body.text());


但是出现问题了,请求就报错:

org.jsoup.UnsupportedMimeTypeException: Unhandled content type. Must be text/*, application/xml, or application/xhtml+xml. Mimetype=application/json;charset=UTF-8, URL=http://www.baidu.com/
	at org.jsoup.helper.HttpConnection$Response.execute(HttpConnection.java:600)
	at org.jsoup.helper.HttpConnection$Response.execute(HttpConnection.java:540)
	at org.jsoup.helper.HttpConnection.execute(HttpConnection.java:227)
	at org.jsoup.helper.HttpConnection.get(HttpConnection.java:216)

当然一看就明白,说没有指定类型。找了如下解决方案:

 Response res = Jsoup.connect(Constant.DATA_URL)
		.header("Accept", "*/*")
		.header("Accept-Encoding", "gzip, deflate")
		.header("Accept-Language","zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3")
		.header("Content-Type", "application/json;charset=UTF-8")
		.header("User-Agent","Mozilla/5.0 (Windows NT 6.1; WOW64; rv:48.0) Gecko/20100101 Firefox/48.0")
		.timeout(10000).ignoreContentType(true).execute();//.get();
String body = res.body();
JSONObject json = JSONObject.fromObject(body);


上面其实关键点在于:ignoreContentType(true) ,这个是忽略请求类型。建议用execute() 去执行,如果用get 去执行的话,返回来是一个 HTML  页面包裹的 JSON  ,你处理起来稍微有点费劲。返回情况如下:

而且你要处理换行,你看到有换行了吧, JSON  正确的格式是一行返回,多行的话转成 JSON  对象的时候就会报错。所以还是推荐用execute() 去执行。

不过我最后还是换做用 HttpConnection  来解决。

InputStreamReader reader = null;
BufferedReader in = null;
try {
	URL url = new URL(Constant.DATA_URL);
	URLConnection connection = url.openConnection();
	connection.setConnectTimeout(1000);
	reader = new InputStreamReader(connection.getInputStream(), "UTF-8");
	in = new BufferedReader(reader);
	String line = null; // 每行内容
	StringBuffer content = new StringBuffer();
	while ((line = in.readLine()) != null) {
		content.append(line);
	}
	if (StringUtils.isNotBlank(content)) {
		String jsonStr = content.toString().replaceAll("\\n", "");
		data = JSONObject.fromObject(jsonStr);
	}
} catch (SocketTimeoutException e) {
	System.out.println("连接超时!!!");
} catch (JSONException e) {
	System.out.println("网站响应不是json格式,无法转化成JSONObject!!!");
} catch (Exception e) {
	System.out.println("连接网址不对或读取流出现异常!!!");
} finally {
	if (in != null) {
		try {
			in.close();
		} catch (IOException e) {
			System.out.println("关闭流出现异常!!!");
		}
	}
	if (reader != null) {
		try {
			reader.close();
		} catch (IOException e) {
			System.out.println("关闭流出现异常!!!");
		}
	}
}


建议API JSON 接口请求,还是用正常的 HTTP  请求吧。

响应数据的解析方式取决于服务器返回数据格式。一般来说,我们可以使用JSON、XML或HTML等格式来处理响应数据。以百度搜索为例,它的搜索结果页面是一个HTML文件,因此我们可以使用Jsoup库来解析HTML文件。 以下是一个使用Jsoup库解析百度搜索结果页面的示例代码: ```java import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; public void request() { okhttp3.OkHttpClient client = new okhttp3.OkHttpClient(); // 构建请求 URL,其中包含搜索关键字 String url = "https://www.baidu.com/s?wd="; Request request = new Request.Builder() .url(url) .build(); // 发起 GET 请求,并获取响应数据 try (Response response = client.newCall(request).execute()) { String responseData = response.body().string(); // 解析响应数据,提取搜索结果等信息 Document doc = Jsoup.parse(responseData); Elements results = doc.select(".result"); for (Element result : results) { String title = result.select(".t a").text(); String summary = result.select(".c-abstract").text(); System.out.println(title); System.out.println(summary); } } catch (IOException e) { e.printStackTrace(); } } ``` 在这个示例中,我们使用Jsoup库将响应数据解析成一个Document对象,然后使用CSS选择器来提取搜索结果的标题和摘要信息。通过对响应数据的解析,我们可以更方便地获取搜索结果等信息,以满足我们的需求。
评论 12
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值