文件与其他参数一起上传

编程

对接方提供的接口样例如下

实现代码如下  

public static String doPostUploadFile(String url, MultipartFile file,Map<String, Object> params){

log.info("请求地址:" + url);

log.info("请求参数:" + params);

String resultStr = null;

CloseableHttpClient httpClient = HttpClients.createDefault();

HttpPost httpPost = new HttpPost(url);

MultipartEntityBuilder builder = MultipartEntityBuilder.create();

builder.setCharset(java.nio.charset.Charset.forName("UTF-8"));

builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);

String filename=file.getOriginalFilename();

try {

builder.addBinaryBody("file",file.getInputStream(), ContentType.DEFAULT_BINARY, filename);

ContentType contentType = ContentType.create(HTTP.PLAIN_TEXT_TYPE, HTTP.UTF_8);

for (Map.Entry<String, Object> entry : params.entrySet()) {

if(entry.getValue() == null)

continue;

builder.addTextBody(entry.getKey(), entry.getValue().toString(), contentType);

}

HttpEntity entity = builder.build();

httpPost.setEntity(entity);

HttpResponse response = httpClient.execute(httpPost);

// 设置连接超时时间

RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(connectTimeout)

.setConnectionRequestTimeout(connectTimeout).setSocketTimeout(connectTimeout).build();

httpPost.setConfig(requestConfig);

HttpEntity responseEntity = response.getEntity();

int code = response.getStatusLine().getStatusCode();

if (responseEntity != null) {

// 将响应内容转换为字符串

resultStr = EntityUtils.toString(responseEntity, java.nio.charset.Charset.forName("UTF-8"));

log.info("返回值:"+resultStr);

}

} catch (IOException e) {

e.printStackTrace();

}

return resultStr;

}

以上是 文件与其他参数一起上传 的全部内容, 来源链接: utcz.com/z/511924.html

回到顶部