使用httpClient 中转上传 multipart/form-data 类型文件
客户端提交上传文件 —> a服务器接收 —> 转发到b服务器进行文件处理或存储
引入依赖:
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.4</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpmime</artifactId>
<version>4.4</version>
</dependency>
上传代码:
import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.ByteArrayBody;
import org.apache.http.entity.mime.content.ContentBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
@Service
public class PutFileServiceImpl extends BaseServiceImpl {
@Override
public BaseResult fileUpload(MultipartFile file) {
BaseResult bslBaseResult = null;
if (file.isEmpty()) {
throw new BusinessException("文件为空,上传失败");
}
String url = "xxxxxxxxxxxxxxx";
String result = null;
try {
HttpPost httpPost = new HttpPost(url);
//注:这里加上Content-Type为multipart/form-data属性会上传失败,报500。
//因为这里面有个boundary参数属性作为mulipart类型请求数据的"分割边界",这个值一般是由浏览器随机生成的,
//如果强行指明很可能导致边界值不一致,就会请求失败。详见 https://blog.csdn.net/xiaojianpitt/article/details/6856536
// httpPost.setHeader("Content-Type", ContentType.MULTIPART_FORM_DATA.toString());
String fileName = file.getOriginalFilename();
ContentBody fileContentBody = new ByteArrayBody(file.getBytes(), fileName);
MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create();
entityBuilder.addPart("file", fileContentBody);
HttpEntity httpEntity = entityBuilder.build();
httpPost.setEntity(httpEntity);
// 执行提交
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpResponse response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
if (entity != null) {
// 将响应内容转换为字符串
result = EntityUtils.toString(entity, StandardCharsets.UTF_8);
// 将响应内容字符串解析为对象
bslBaseResult = JSONObject.parseObject(result, BslBaseResult.class);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
httpClient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return bslBaseResult;
}
}