下面是“java中httpclient封装post请求和get的请求实例”的完整攻略:
一、介绍httpclient
HttpClient是Apache Jakarta Common下的子项目,用来提供高效的、最新的、功能丰富的支持HTTP协议的客户端编程工具包,并且它支持HTTP协议最新的版本和建议,比如1.1和RFC2616。HttpClient实现了所有HTTP方法(GET、POST、PUT、DELETE、HEAD、OPTIONS等),还支持HTTPS(基于SSL协议)。
HttpClient连接管理的机制及连接池功能都是Apache httpclient独有的功能。
二、httpclient封装get请求实例
/**
* HttpClient 进行 GET 请求
*/
public static String doGet(String url, Map<String, String> headers) throws Exception {
//创建httpClient实例,获取HttpClient对象
CloseableHttpClient httpClient = HttpClientBuilder.create().build();
try {
//创建httpGET请求
HttpGet httpGet = new HttpGet(url);
//设置headers
setHeader(headers, httpGet);
//执行http GET请求
CloseableHttpResponse httpResponse = httpClient.execute(httpGet);
try {
//获取响应内容
HttpEntity entity = httpResponse.getEntity();
//将响应内容转换成String类型
String responseBody = EntityUtils.toString(entity, Charset.forName("UTF-8"));
//打印响应内容
System.out.println("responseBody: " + responseBody);
return responseBody;
} finally {
//释放连接
httpResponse.close();
}
} finally {
//关闭httpClient
httpClient.close();
}
}
private static void setHeader(Map<String, String> headers, HttpRequestBase httpRequestBase) {
if (headers == null || headers.isEmpty()) {
return;
}
for (Map.Entry<String, String> entry : headers.entrySet()) {
httpRequestBase.setHeader(entry.getKey(), entry.getValue());
}
}
三、httpclient封装post请求实例
/**
* httpClient 进行 POST 请求
*/
public static String doPost(String url, Map<String, String> headers, Map<String, String> params) throws Exception {
//创建httpClient实例,获取HttpClient对象
CloseableHttpClient httpClient = HttpClientBuilder.create().build();
try {
//创建httpPost请求
HttpPost httpPost = new HttpPost(url);
//设置headers
setHeader(headers, httpPost);
//设置参数
setParams(params, httpPost);
//执行http Post请求
CloseableHttpResponse httpResponse = httpClient.execute(httpPost);
try {
//获取响应内容
HttpEntity entity = httpResponse.getEntity();
//将响应内容转换成String类型
String responseBody = EntityUtils.toString(entity, Charset.forName("UTF-8"));
//打印响应内容
System.out.println("responseBody: " + responseBody);
return responseBody;
} finally {
//释放连接
httpResponse.close();
}
} finally {
//关闭httpClient
httpClient.close();
}
}
private static void setParams(Map<String, String> params, HttpPost httpPost) throws UnsupportedEncodingException {
if (params == null || params.isEmpty()) {
return;
}
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
for (Map.Entry<String, String> entry : params.entrySet()) {
nameValuePairs.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
}
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs, "UTF-8"));
}
以上就是我对“java中httpclient封装post请求和get的请求实例”的完整攻略,希望能对您有所帮助。
本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:java中httpclient封装post请求和get的请求实例 - Python技术站