HttpClient 是Apache Jakarta Common 下的子项目,可以用来提供高效的、最新的、功能丰富的支持 HTTP 协议的客户端编程工具包,并且它支持 HTTP 协议最新的版本和建议。
get---里面的东西放在 请求头中 post--里面的东西放在body请求正文中
HttpClient发送请求的步骤:
(1)创建HttpClient对象。
(2)创建请求方法的实例,并指定请求URL。如果需要发送GET请求,创建HttpGet对象;如果需要发送POST请求,创建HttpPost对象。
(3) 如果需要发送请求参数,可调用HttpGet、HttpPost共同的setParams(HetpParams params)方法来添加请求参数;对于HttpPost对象而言 也可调用setEntity(HttpEntity entity)方法来设置请求参数。
(4)调用HttpClient对象的execute(HttpUriRequest request)发送请求,该方法返回一个HttpResponse。
(5)调用HttpResponse的getAllHeaders()、getHeaders(String name)等方法可获取服务器的响应头;调用HttpResponse的getEntity()方法可获取HttpEntity对象,该对象包装了服务器的响应内容。程序可通过该对象获取服务器的响应内容。
(6) 释放连接。无论执行方法是否成功,都必须释放连接
@Test
public void testAir()throws Exception {
CloseableHttpClient httpClient = HttpClients.createDefault();
String param = "city=北京";
HttpGet httpGet = getHttpGet("https://www.sojson.com/open/api/weather/json.shtml",param);
new HttpGet();
CloseableHttpResponse httpResponse = httpClient.execute(httpGet);
String msg = EntityUtils.toString(httpResponse.getEntity(),"utf-8");
System.out.println(msg);
}
public static HttpGet getHttpGet(String url,String param) throws Exception {
//param = URLEncoder.encode(param,"utf-8") ;
System.out.println(url+"?"+param);
HttpGet httpGet = new HttpGet(url+"?"+param);
return httpGet;
}
Post调用代码
public static String postWithHeadersAndStringEntity(String url, Map<String, String> headers, String str) {
CloseableHttpClient closeableHttpClient = null;
CloseableHttpResponse closeableHttpResponse = null;
String result = null;
try {
//以post方式
HttpPost httpPost = new HttpPost(url);
HttpUtil.setHeader(httpPost, headers);//调用工具类HttpUtil 把headers 添加进去
StringEntity entity = new StringEntity(str, "UTF-8");
httpPost.setEntity(entity);//把参数添加进去post的参数 是存放于entity(body实体)中的
//CloseableHttpClient 这是个接口
closeableHttpClient = HttpClients.createDefault();
//执行post 的到响应对象
closeableHttpResponse = closeableHttpClient.execute(httpPost);
//提取响应对象里的结果转换为String类型
result = EntityUtils.toString(closeableHttpResponse.getEntity());
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
closeableHttpResponse.close();
closeableHttpClient.close();
} catch (Exception e) {
e.printStackTrace();
}
}
return result;
}