目录
简介
使用步骤
post请求
get请求
目前前后端项目分离的项目,通过Resutful风格居多。当需要调用第三方api的时,HttpClient则派上用场。
HttpClient是属于Apache Jakarta Common 下的一个工具包,可以实现所有Http的请求方法,如Get、Post、Put等,支持Https协议,支持代理服务器等。
如下将对post请求和get请求做代码展示
首先定义一个返回类
@ApiModel(value = "响应")
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Result implements Serializable {
/**
* 编码:200表示成功,其他值表示失败
*/
@ApiModelProperty(value = "编码:200表示成功,其他值表示失败")
private int code ;
/**
* 消息内容
*/
@ApiModelProperty(value = "消息内容")
private String msg ;
/**
* 响应数据
*/
@ApiModelProperty(value = "响应数据")
private T data;
/** 余下代码根据各系统定义 **/
}
这边主要演示常见的json请求和form-data请求
post中的json请求:
定义入参:String类型的url,封装请求头用Map
/**
* post请求
* @param url http://***.com/test
* @param headers 请求头
* @param body 请求体
* @return
*/
public static Result doPost(String url, Map headers, String body) {
Result result = new Result();
String httpCharset = "utf-8";
// 创建HttpClient对象
CloseableHttpClient httpClient = HttpClients.createDefault();
// 创建HttpResponse对象
CloseableHttpResponse response = null;
try {
try {
// 创建HttpPost对象
HttpPost post = new HttpPost(url);
// 封装请求头
if (null != headers) {
headers.keySet().forEach(key -> {
post.addHeader(key, headers.get(key));
});
}
// 封装请求体
if (StringUtils.isNotBlank(body)) {
// 请求体主要封装在HttpEntity中
post.setEntity(new StringEntity(body, Charset.forName(httpCharset)));
}
response = httpClient.execute(post);
// 处理响应
result.setCode(response.getStatusLine().getStatusCode());
result.setData(EntityUtils.toString(response.getEntity(), Charset.forName(httpCharset)));
} catch (IOException e) {
logger.error("post链接失败:" + e.getMessage());
} finally {
// 释放连接
response.close();
}
} catch (IOException e) {
logger.error("post关闭response失败:" + e.getMessage());
}
return result;
}
post中的form-data请求:
form-data顾名思义为表单请求,其请求格式主要为application/x-www-form-urlencoded和multipart/form-data:
这两者的区别:application/x-www-form-urlencoded会将表单中的数据经过urlencode编码后放在request body,multipart/form-data主要处理二进制类型,文件上传中的接口会用到
定义入参:String类型的url,封装请求头用Map
/**
* post(form-data)请求
* @param url http://***.com/test
* @param headers 请求头
* @param body 请求体
* @return
*/
public static Result doPostFormData(String url, Map headers, Map paramMap) {
Result result = new Result();
String httpCharset = "utf-8";
// 创建HttpClient对象
CloseableHttpClient httpClient = HttpClients.createDefault();
// 创建HttpResponse对象
CloseableHttpResponse response = null;
try {
try {
// 创建HttpPost对象
HttpPost post = new HttpPost(url);
List params = new ArrayList<>();
//建立一个NameValuePair数组,用于存储欲传送的参数
paramMap.keySet().forEach(key -> {
params.add(new BasicNameValuePair(key, paramMap.get(key)));
});
// 封装请求头
if (null != headers) {
// "Content-Type","application/x-www-form-urlencoded"
// "Content-Type","multipart/form-data"
headers.keySet().forEach(key -> {
post.addHeader(key, headers.get(key));
});
}
//设置编码
post.setEntity(new UrlEncodedFormEntity(params, httpCharset));
response = httpClient.execute(post);
// 处理响应
result.setCode(response.getStatusLine().getStatusCode());
result.setData(EntityUtils.toString(response.getEntity(), Charset.forName(httpCharset)));
} catch (IOException e) {
logger.error("post链接失败:" + e.getMessage());
} finally {
// 释放连接
response.close();
}
} catch (IOException e) {
logger.error("post关闭response失败:" + e.getMessage());
}
return result;
}
get请求由于可以将参数以&和?拼接在url后面,因此省去了处理httpEntity
定义入参:String类型的url,封装请求头用Map
/**
* get请求
* @param url http://***.com/test?key=1&name=quliuwuxin
* @param headers 请求头
* @return
*/
public static Result doGet(String url, Map headers) {
Result result = new Result();
String httpCharset = "utf-8";
// 创建HttpClient对象
CloseableHttpClient httpClient = HttpClients.createDefault();
// 创建HttpResponse对象
CloseableHttpResponse response = null;
try {
try {
// HttpGet
HttpGet get = new HttpGet(url);
// 封装请求头
if (null != headers) {
headers.keySet().forEach(key -> {
get.addHeader(key, headers.get(key));
});
}
response = httpClient.execute(get);
// 处理响应
result.setCode(response.getStatusLine().getStatusCode());
result.setData(EntityUtils.toString(response.getEntity(), Charset.forName(httpCharset)));
} catch (IOException e) {
logger.error("get链接失败:" + e.getMessage());
} finally {
// 释放连接
response.close();
}
} catch (IOException e) {
logger.error("get关闭response失败:" + e.getMessage());
}
return result;
}
调用完数据后,一般是对数据的清洗,常用到com.alibaba.fastjson工具类
引入包
org.apache.httpcomponents
httpclient
4.5.2
com.alibaba
fastjson
1.2.72