转载请注明出处:
项目中有遇到http使用formData请求传输文件,在此记录一下
1.依赖jar包:
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.2</version>
</dependency>
2.代码:
// 定义httpClient和response
CloseableHttpClient httpClient = HttpClientBuilder.create().build();;
CloseableHttpResponse response = null;
try {
// 定义Post请求
HttpPost httpPost = new HttpPost(uri);
// 设置配置
Builder builder = createBuilder();
RequestConfig config = null;
// 是否开启代理模式访问
if (enabled) {
HttpHost proxy = new HttpHost(host, port, Proxy.Type.HTTP.toString());
config = builder.setProxy(proxy).build();
} else {
config = builder.build();
}
httpPost.setConfig(config);
// 设置请求头
// httpPost.setHeader(FucdnStrConstant.ACCEPT.getConstant(), MediaType.MULTIPART_FORM_DATA_VALUE);
httpPost.setHeader(FucdnStrConstant.CONTENT_TYPE.getConstant(), MediaType.MULTIPART_FORM_DATA_VALUE);
// 发送请求得到返回数据
httpPost.setEntity(fileBuilder.build());
// 得到响应
response = httpClient.execute(httpPost);
// 状态码
int statusCode = response.getStatusLine().getStatusCode();
// 响应内容
HttpEntity entity = response.getEntity();
// 响应内容
String responseContent = EntityUtils.toString(entity);
} catch (Exception e) {
throw new FucdnException(e);
} finally {
// 关闭流
Utils.closeStream(response);
Utils.closeStream(httpClient);
}
private Builder createBuilder() {
// init Builder and init TIME_OUT
return RequestConfig.custom().setSocketTimeout(20000).setConnectTimeout(20000)
.setConnectionRequestTimeout(20000);
}
public static void closeStream(Closeable c) {
// 流不为空
if (c != null) {
try {
// 流关闭
c.close();
} catch (IOException ex) {
LOGGER.error("closeStream failed", ex);
}
}
}