因公司需要,出现一个接口通过网络请求调用另外一个接口的情况,该接口恰好是导入excel文件,第一个接口负责把文件转发到第二个接口,所以第一个接口就需要把动态构建MultipartFile表单,才能调成功第二个处理业务的接口。各种百度,各种不不好使,最终,终于在各路大神的指导下完成了。
踩了一天的坑,总结出来如下代码
/**
*
* @return
*/
@PostMapping(value = "/import")
public Result importSolr(@RequestParam(name = "file") MultipartFile file){
Result result = null;
try {
String originalFilename = file.getOriginalFilename();
if (!ExcelUtils.isExcel(originalFilename)){
return Result.buildErrorMsg("请导入Excel文件","0010010002");
}
MultipartEntityBuilder fileBuilder = MultipartEntityBuilder.create();
fileBuilder.setMode(HttpMultipartMode.RFC6532);
fileBuilder.addBinaryBody("file",file.getInputStream(), ContentType.create("multipart/form-data"),file.getOriginalFilename());
HttpEntity build = fileBuilder.build();
HttpPost request = new HttpPost(WebConfig.HOST_KNOWLEDGE + WebConfig.HOST_KNOWLEDGE_SOLRIMPORT);
request.setEntity(build);
HttpClient httpClient = HttpClients.createDefault();
HttpResponse httpResponse = httpClient.execute(request);
result = HttpUtils.buildHttpResponse(httpResponse);
} catch (IOException e) {
e.printStackTrace();
result = Result.buildErrorMsg("系统发生异常","0010010007");
}
return result;
}