3行代码 java http请求 httpclient 接收json

IT黑名单 2017-11-3 10:53:21

依赖了Apache httpclient,结果用JSON接收,依赖了fastjson
maven依赖:

<dependency>
	<groupId>org.apache.httpcomponents</groupId>
	<artifactId>httpclient</artifactId>
	<version>4.5</version>
</dependency>
<dependency>
	<groupId>com.alibaba</groupId>
	<artifactId>fastjson</artifactId>
	<version>1.2.6</version>
</dependency>
代码
HttpResponse response = HttpClients.createDefault().execute(new HttpGet("http://www.itblacklist.cn/"));
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
	JSONObject obj = JSONObject.parseObject(EntityUtils.toString(response.getEntity()));
}

到这里结束,下面的可以略过。以上代码片段等同于:

CloseableHttpClient client = HttpClients.createDefault();
HttpGet request = new HttpGet("http://www.itblacklist.cn/");
HttpResponse response = client.execute(request);
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
	String responseStr = EntityUtils.toString(response.getEntity());
	JSONObject obj = JSONObject.parseObject(responseStr);
}




转载请注明来源【IT黑名单

本文链接:http://blog.itblacklist.cn/20171103/8462.html

© Copyright 2016 IT黑名单 Inc.All Rights Reserved. 豫ICP备15018592号-2