HttpClient 是 Apache Jakarta Common 下的子项目,可以用来提供高效的、最新的、功能丰富的支持 HTTP 协议的客户端编程工具包,并且它支持 HTTP 协议最新的版本和建议。
使用HttpClient发送请求、接收响应很简单,一般需要如下几步即可:
1.创建CloseableHttpClient对象。
2.创建请求方法的实例,并指定请求URL。如果需要发送GET请求,创建HttpGet对象;如果需要发送POST请求,创建HttpPost对象。
3.如果需要发送请求参数,可可调用setEntity(HttpEntity entity)方法来设置请求参数。setParams方法已过时(4.4.1版本)。
4.调用HttpGet、HttpPost对象的setHeader(String name, String value)方法设置header信息,或者调用setHeaders(Header[] headers)设置一组header信息。
5.调用CloseableHttpClient对象的execute(HttpUriRequest request)发送请求,该方法返回一个CloseableHttpResponse。
6.调用HttpResponse的getEntity()方法可获取HttpEntity对象,该对象包装了服务器的响应内容。程序可通过该对象获取服务器的响应内容;调用CloseableHttpResponse的getAllHeaders()、getHeaders(String name)等方法可获取服务器的响应头。
7.释放连接。无论执行方法是否成功,都必须释放连接
public class HttpClientUtil {
/**url是请求地址,map是要传递的参数**/
public static String URLPost(String url,Map<String,String> map) throws IOException {
String str = JSONObject.toJSONString(map);
String result = "";
System.out.println("发送给对端的json串为:"+str);
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
// 设置请求的header
httpPost.addHeader("Content-Type", "application/json;charset=utf-8");
StringEntity entity = new StringEntity(str, "utf-8");
entity.setContentEncoding("UTF-8");
httpPost.setEntity(entity);
HttpResponse response = httpClient.execute(httpPost);
result = EntityUtils.toString(response.getEntity(), "utf-8");
return result;
}
}
/*httpPost.setHeader("Content-type", "application/x-www-form-urlencoded");
httpPost.setHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");*/