HttpClient请求工具类
2024-10-07 19:20:53
package com.yangche.utils; import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.*;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.springframework.util.StringUtils; import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map; public class HttpClientUtil {
public static String doGet(String url, Map<String,Object> param){
//创建httpclient对象
CloseableHttpClient httpClient = HttpClients.createDefault();
String resultString="";
CloseableHttpResponse response=null;
try {
URIBuilder builder=new URIBuilder(url);
if(param!=null){
for (String key:param.keySet()){
if(param.get(key) instanceof List){
List list=(List)param.get(key);
for (Object liString:list){
builder.addParameter(key,String.valueOf(liString));
}
}else {
builder.addParameter(key,String.valueOf(param.get(key)));
}
}
}
URI uri=builder.build();
//创建httpGet请求
HttpGet httpGet=new HttpGet(uri);
//执行请求
response=httpClient.execute(httpGet);
resultString= EntityUtils.toString(response.getEntity(),"UTF-8");
} catch (URISyntaxException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
if(response!=null){
response.close();
}
httpClient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return resultString;
}
public static String doGet(String url){
return doGet(url,null);
}
public static String doPost(String url,Map<String,String> param){
//创建httpclient对象
CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse response=null;
String resultString="";
//创建httpPost请求
HttpPost httpPost = new HttpPost(url);
//创建参数列表
if(param!=null){
List<NameValuePair> paramList=new ArrayList<>();
for (String key:param.keySet()){
paramList.add(new BasicNameValuePair(key,param.get(key)));
}
try {
//模拟表单
UrlEncodedFormEntity entity=new UrlEncodedFormEntity(paramList);
httpPost.setEntity(entity);
//执行http请求
response=httpClient.execute(httpPost);
resultString=EntityUtils.toString(response.getEntity(),"UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
response.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return resultString;
}
public static String doPost(String url){
return doPost(url,null);
} /**
* restful请求
* @param url
* @param requestType 请求类型:post、delete、patch
* @param json
* @return
*/
public static String doRequest(String url,String requestType,String json){
//创建HttpClient对象
CloseableHttpClient httpClient=HttpClients.createDefault();
CloseableHttpResponse response=null;
String resultString="";
try {
//创建不同类型的请求
HttpPost httpPost=new HttpPost(url);
HttpDeleteWithBody httpDelete =new HttpDeleteWithBody(url);
HttpPatch httpPatch=new HttpPatch(url);
//创建请求内容
StringEntity entity=new StringEntity(json, ContentType.APPLICATION_JSON);
//执行http请求
if(!StringUtils.isEmpty(requestType)&&requestType.equalsIgnoreCase("post")){
httpPost.setEntity(entity);
response=httpClient.execute(httpPost);
}else if(!StringUtils.isEmpty(requestType)&&requestType.equalsIgnoreCase("delete")){
httpDelete.setEntity(entity);
response=httpClient.execute(httpDelete);
}else if(!StringUtils.isEmpty(requestType)&&requestType.equalsIgnoreCase("patch")){
httpPatch.setEntity(entity);
response=httpClient.execute(httpPatch);
}
resultString=EntityUtils.toString(response.getEntity(),"UTF-8");
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
response.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return resultString;
} private static class HttpDeleteWithBody extends HttpEntityEnclosingRequestBase {
public static final String METHOD_NAME="DELETE";
@Override
public String getMethod() {
return METHOD_NAME;
}
public HttpDeleteWithBody (final String uri){
super();
setURI(URI.create(uri));
}
public HttpDeleteWithBody (final URI uri){
super();
setURI(uri);
}
public HttpDeleteWithBody(){
super();
}
}
}
以上所需的maven依赖如下:
<!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpcore -->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpcore</artifactId>
<version>4.4.10</version>
</dependency> <!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient -->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.6</version>
</dependency>
最新文章
- 配置与使用 Git与Github
- BookBlock - 效果非常真实的书本翻页预览
- python peewee.ImproperlyConfigured: MySQLdb or PyMySQL must be installed.
- kaili linux中文乱码
- BZOJ3828 : [Poi2014]Criminals
- C#对XML、JSON等格式的解析
- Ajax - 登录
- 基于.NET MVC的高性能IOC插件化架构
- ios的位置和方向(来自苹果官方文档,仅供简单参考)
- struts2框架学习笔记3:获取servletAPI
- elk系统通过nginx添加对kibana的登录认证
- 域名直接访问应用程序-不加端口号&;不加路径名
- ssm controller层 junit单元测试
- OpenLayers 比较有用的对象和属性
- python pytest测试框架介绍四----pytest-html插件html带错误截图及失败重测机制
- c语言格式大整理
- POJ 1836 Alignment (双向DP)
- BZOJ2820 YY的GCD 【莫比乌斯反演】
- POJ2142(扩展欧几里得)
- Python 利用循环画散点图