最近做第三方api对接, 用到http文件上传和普通的post请求所以记录下.
分别引用了这两位老哥的文档
Apache HttpClient 4.5 Multipart Upload Request Example
HttpClient超时设置详解
在引入jar包上, 第一个链接引用的是
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.3</version>
</dependency>
<!-- Apache HttpClient Mime -->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpmime</artifactId>
<version>4.5.3</version>
</dependency>
不知道为何其实httpmime里边有包含httpclient的jar包的,但是外这篇外文也有引用.但是无所谓拉.
下面直接上代码post请求上传文件
/**
* http post方式上传文件
* httpPost
* @param url
* @param headers 请求头信息
* @param bodyMap 请求体信息 只支持文件,可以多文件,不过后端接受文件比较麻烦 因为每个都文件都有一个name,
* 而spring获取文件都是通过@RequestParam("uploadFile") MultipartFile file的方式来获取
* @return org.apache.http.HttpEntity
*/
public static String httpPost(String url, Map<String, String> headers, Map<String, File> bodyMap) throws IOException {
CloseableHttpClient httpClient = HttpClients.createDefault();
// result
String result = "";
try {
HttpPost httpPost = new HttpPost(url);
// 设置请求和传输超时时间
RequestConfig requestConfig = RequestConfig.custom()
.setConnectTimeout(10_000)
.setConnectionRequestTimeout(10_000)
.setSocketTimeout(10_000).build();
httpPost.setConfig(requestConfig);
headers.forEach((key, value) -> httpPost.setHeader(key, value));
//构造请求体
MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create();
// 以浏览器兼容模式运行,防止文件名乱码。
entityBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
// 设置二进制的方式上传文件addBinaryBody() 如果是表单 用addPart() 主要用哪一个看需求
if (bodyMap != null) {
bodyMap.forEach((key, value) -> entityBuilder.addBinaryBody(key, value));
}
HttpEntity reqEntity = entityBuilder.setCharset(CharsetUtils.get("UTF-8")).build();
httpPost.setEntity(reqEntity);
// System.out.println("发起请求的页面地址 " + httpPost.getRequestLine());
// 发起请求 并返回请求的响应
CloseableHttpResponse response = httpClient.execute(httpPost);
try {
// 获取响应对象
HttpEntity resEntity = response.getEntity();
if (resEntity != null) {
result = EntityUtils.toString(resEntity, Charset.forName("UTF-8"));
}
/***
// 想看可以打开注释
// 打印响应状态
// System.out.println("response StatusLin:" + response.getStatusLine());
// 打印http状态码
// System.out.println("response code:" + response.getStatusLine().getStatusCode());
if (resEntity != null) {
// 响应长度
System.out.println("Response content length: "
+ resEntity.getContentLength());
// 响应内容
System.out.println("response content: " + result);
}
*/
// 销毁
EntityUtils.consume(resEntity);
} finally {
if (response != null) {
response.close();
}
}
} finally {
if (httpClient != null) {
httpClient.close();
}
}
return result;
}