HttpClien用multipart/form-data上传文件方法
1.接口调用封装:
定义map
List item
```java
Map<String, ContentBody> reqParam = new HashMap<String, ContentBody>();
/*
* 封装参数
* */
ContentType contentType = ContentType.create("text/plain", Charset.forName("UTF-8"));
reqParam.put("analyzeType", new StringBody(projectAiModel.getSn(), ContentType.MULTIPART_FORM_DATA));
reqParam.put("deviceID", new StringBody(deviceId, ContentType.MULTIPART_FORM_DATA));
reqParam.put("extend", new StringBody("", ContentType.MULTIPART_FORM_DATA));
reqParam.put("file", new FileBody(new File(multipartFile.getName())));
reqParam.put("fileUri", new StringBody(url, ContentType.MULTIPART_FORM_DATA));
reqParam.put("filterDuplicates", new StringBody(String.valueOf(true), ContentType.MULTIPART_FORM_DATA));
reqParam.put("objectType", new StringBody(AnalyzeMaterialEnum.IMAGE.toString(), ContentType.MULTIPART_FORM_DATA));
reqParam.put("requestID", new StringBody(requestId, ContentType.MULTIPART_FORM_DATA));
/*
* 上传图片,调用以下工具类`在这里插入代码片`
* */
String post = HttpRequestUtil.doPost(aiSubscriber.getUrl(), athorization, reqParam);
**2.HttpRequestUtil (接口调用工具类)**
/**
* Created by wdy on 2021/7/07
* 接口调用工具类
*/
public class HttpRequestUtil {
private static CloseableHttpClient httpClient;
static {
PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
cm.setMaxTotal(100);
cm.setDefaultMaxPerRoute(20);
cm.setDefaultMaxPerRoute(50);
httpClient = HttpClients.custom().setConnectionManager(cm).build();
}
public static String doGet(String url) {
CloseableHttpResponse response = null;
BufferedReader in = null;
String result = "";
try {
HttpGet httpGet = new HttpGet(url);
RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(30000).setConnectionRequestTimeout(30000).setSocketTimeout(30000).build();
httpGet.setConfig(requestConfig);
httpGet.setConfig(requestConfig);
httpGet.addHeader("Content-type", "application/json; charset=utf-8");
httpGet.setHeader("Accept", "application/json");
response = httpClient.execute(httpGet);
in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
StringBuffer sb = new StringBuffer("");
String line = "";
String NL = System.getProperty("line.separator");
while ((line = in.readLine()) != null) {
sb.append(line + NL);
}
in.close();
result = sb.toString();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (null != response) {
response.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return result;
}
public static String doPost(String url, String athorization, Map<String, ContentBody> reqParam) throws ClientProtocolException, IOException {
CloseableHttpClient httpclient = HttpClients.createDefault();
try {
// 创建httpget.
HttpPost httppost = new HttpPost(url);
//setConnectTimeout:设置连接超时时间,单位毫秒。setConnectionRequestTimeout:设置从connect Manager获取Connection 超时时间,单位毫秒。这个属性是新加的属性,因为目前版本是可以共享连接池的。setSocketTimeout:请求获取数据的超时时间,单位毫秒。 如果访问一个接口,多少时间内无法返回数据,就直接放弃此次调用。
RequestConfig defaultRequestConfig = RequestConfig.custom().setConnectTimeout(5000).setConnectionRequestTimeout(5000).setSocketTimeout(15000).build();
httppost.setConfig(defaultRequestConfig);
httppost.addHeader("Authorization", athorization);
System.out.println("executing request " + httppost.getURI());
MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
for (Map.Entry<String, ContentBody> param : reqParam.entrySet()) {
multipartEntityBuilder.addPart(param.getKey(), param.getValue());
}
HttpEntity reqEntity = multipartEntityBuilder.build();
httppost.setEntity(reqEntity);
// 执行post请求.
CloseableHttpResponse response = httpclient.execute(httppost);
System.out.println("got response");
try {
// 获取响应实体
HttpEntity entity = response.getEntity();
//System.out.println("--------------------------------------");
// 打印响应状态
//System.out.println(response.getStatusLine());
if (entity != null) {
return EntityUtils.toString(entity, Charset.forName("UTF-8"));
}
//System.out.println("------------------------------------");
} finally {
response.close();
}
} finally {
// 关闭连接,释放资源
try {
httpclient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
}