下面我将详细讲解“httpclient 请求http数据,json转map的实例”的完整攻略:
使用httpclient发送http请求
Apache的HttpComponents库提供了一个HttpClient类,可以用来发送HTTP请求。下面是使用httpclient发送http请求的步骤:
- 创建HttpClient对象。HttpClient是线程安全的,所以可以在多个线程之间共享一个实例对象。
CloseableHttpClient httpClient = HttpClients.createDefault();
- 创建请求对象。目前HttpClient支持5种请求方式:GET、POST、PUT、DELETE、HEAD。
HttpGet httpGet = new HttpGet(url);
- 发送请求,获取响应。
CloseableHttpResponse httpResponse = httpClient.execute(httpGet);
- 处理响应结果。
String result = EntityUtils.toString(httpResponse.getEntity(), "UTF-8");
将json字符串转为map对象
可以使用Gson库来将json字符串转为java对象。下面是将json字符串转为map对象的代码示例:
String json = "{\"name\":\"Tom\",\"age\":20}";
Gson gson = new Gson();
Map<String, Object> map = gson.fromJson(json, new TypeToken<Map<String, Object>>(){}.getType());
完整实例
下面展示将http请求的响应结果转为map对象的完整示例:
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpGet httpGet = new HttpGet(url);
try {
CloseableHttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity entity = httpResponse.getEntity();
if (entity != null) {
String result = EntityUtils.toString(entity, "UTF-8");
Gson gson = new Gson();
Map<String, Object> map = gson.fromJson(result, new TypeToken<Map<String, Object>>(){}.getType());
System.out.println(map);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
httpGet.releaseConnection();
}
这是一个通过httpclient发送http请求,将响应结果转为map对象的完整实例。我们只需要将其中的url替换成我们需要请求的网址即可。
The End


大气响应式网络建站服务公司织梦模板
高端大气html5设计公司网站源码
织梦dede网页模板下载素材销售下载站平台(带会员中心带筛选)
财税代理公司注册代理记账网站织梦模板(带手机端)
成人高考自考在职研究生教育机构网站源码(带手机端)
高端HTML5响应式企业集团通用类网站织梦模板(自适应手机端)