利用springboot进行文件接口请求,首先配置pom文件,添加以下内容:
<!--带文件上传HTTP client配置-->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.2</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpmime</artifactId>
<version>4.5.2</version>
</dependency>
其次,为业务代码:
@RequestMapping(value = "/upload", method = RequestMethod.POST)
public @ResponseBody Result<Object> upload(MultipartHttpServletRequest request, HttpSession httpSession) throws Exception{
JoyCard joyCard = joyCardService.importOnetimeDataPlanStatus();
if(!(joyCard.getStatus() == 2 || joyCard.getStatus() == 3)){
return new ResultBuilder<>().message(1, "上一次csv导入未处理完全,请核实!").build();
}
Iterator<String> itr = request.getFileNames();
MultipartFile mpf = null;
//SysUser user = (SysUser) SecurityUtils.getSubject().getPrincipal();
String csvUrl = "";
try {
while (itr.hasNext()) {
mpf = request.getFile(itr.next());
String lastName = mpf.getOriginalFilename().substring(mpf.getOriginalFilename().lastIndexOf(".")+1);
if(!(lastName.equals("csv"))){
return new ResultBuilder<>().message(1, "请上传.csv格式的文件!").build();
}
FileMeta fileMeta = new FileMeta();
fileMeta.setName(mpf.getOriginalFilename());
fileMeta.setSize(mpf.getSize() / 1024 + " Kb");
fileMeta.setType(mpf.getContentType());
try {
fileMeta.setBytes(mpf.getBytes());
File folder = new File(uploadPath + "/csv/");
if (!folder.exists()) {
folder.mkdirs();
}
String location = uploadPath + "/csv/" + mpf.getOriginalFilename();
File file = new File(location);
//拷贝路径
FileCopyUtils.copy(mpf.getBytes(), new FileOutputStream(file));
//设置上传路径
fileMeta.setLocation("/upload/csv/" + mpf.getOriginalFilename());
csvUrl = location;
} catch (Exception e) {
e.printStackTrace();
}
}
} catch (Exception e) {
logger.error("", e);
return new ResultBuilder<>().message(1, "导入发生错误, 请检查文件格式!").build();
}
joyCardService.importOnetimeDataPlan(csvUrl);
return new ResultBuilder<>().data("").build();
}
//根据上传csv文件
public void importOnetimeDataPlan(String csvUrl) throws Exception{
String resultData = "";
// 创建httppost对象
HttpPost post = null;
//创建httpclient对象
CloseableHttpClient client = HttpClients.createDefault();
String url = "http://xxx/xxx";
// 创建uri
post = new HttpPost(url);
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.addBinaryBody("csv", new File(csvUrl));// 文件路径
builder.addTextBody("appId", "");//设置请求参数
builder.addTextBody("appSecret", "");//设置请求参数
builder.addTextBody("", "");//设置请求参数
builder.addTextBody("", "");//设置请求参数
HttpEntity entity = builder.build();// 生成 HTTP POST 实体
post.setEntity(entity);//设置请求参数 );
CloseableHttpResponse response = client.execute(post);
//获取结果实体
HttpEntity results = response.getEntity();
String string = "";
if (results != null) {
//按指定编码转换结果实体为String类型
string = EntityUtils.toString(results, "UTF-8");
logger.info("接口返回信息:"+string);
}
//释放
EntityUtils.consume(entity);
//释放链接
response.close();
}