下面我将详细讲解“httpclient 请求http数据,json转map的实例”的完整攻略:
Apache的HttpComponents库提供了一个HttpClient类,可以用来发送HTTP请求。下面是使用httpclient发送http请求的步骤:
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpGet httpGet = new HttpGet(url);
CloseableHttpResponse httpResponse = httpClient.execute(httpGet);
String result = EntityUtils.toString(httpResponse.getEntity(), "UTF-8");
可以使用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替换成我们需要请求的网址即可。