后端构造post请求,调用上传图片、pdf文件的外部接口


一、需求:

    前端multipartfile 上传文件,后端接收后构造post请求,调用外部接口,传送文件流及其他参数

二、内容包括:

    1.前端postman调用上传接口

    2.后端接收multipartfile文件

    3.后端用httpclient构造post请求

三、代码

@PostMapping(value ="uploadImage")

public void uploadImage(Model model, @RequestParam(value ="image") MultipartFile image, String label) {

log.info("=============uploadImage  start=================");

    log.info("图像处理的标签"+label);

    Map data =new HashMap();

    log.info("开始post请求构造======");

    String url ="http://ip:port/mytest/fileup";//服务端要调用的外部接口

    Map resultMap =new HashMap();

    //httpclients构造post请求

    CloseableHttpClient httpClient = HttpClients.createDefault();

    try {

log.info("post请求的url"+url);

        HttpPost httpPost =new HttpPost(url);

        //HttpMultipartMode.RFC6532参数的设定是为避免文件名为中文时乱码

        MultipartEntityBuilder builder = MultipartEntityBuilder.create().setMode(HttpMultipartMode.RFC6532);

        String originFileName =null;

        originFileName = image.getOriginalFilename();

        //    File file1 = new File("/home/temp/下载/1200-560.jpg"); //测试外部接口直接上传本地图片

        //builder.addBinaryBody("image", image.getInputStream(), ContentType.MULTIPART_FORM_DATA, originFileName);// 设置上传文件流(需要是输出流),设置contentType的类型

        //重中之重!!!!contentType的类型的设置  如果你只传一个文件可以设置成ContentType.MULTIPART_FORM_DATA  如果你传多个文件必须设置如下格式图片类型---》image/jpeg pdf类型---》application/pdf  其他类型可百度  重点是不能笼统的设置成MULTIPART_FORM_DATA

        builder.addBinaryBody("image", image.getInputStream(), "image/jpeg", originFileName);

        builder.addBinaryBody("pdf", image.getInputStream(), "application/pdf", originFileName);

        builder.addTextBody("label",label);//post请求中的其他参数

        //    log.info("上传图的标签label"+label);

        HttpEntity entity = builder.build();

        httpPost.setEntity(entity);

        HttpResponse response = httpClient.execute(httpPost);// 执行提交

        HttpEntity responseEntity = response.getEntity();//接收调用外部接口返回的内容

        if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK){//    String imageUrl = stringStringMap.get("data"); //    data.put("path",imageUrl);

            result = EntityUtils.toString(responseEntity, Charset.forName("UTF-8"));

        }

logger.info("http请求结果是:"+result);

    }catch (Exception e) {

model.addAttribute("code", "错误码");

        model.addAttribute("message","错误的提示信息");

    }finally {//处理结束后关闭httpclient的链接

        try {

httpClient.close();

        }catch (IOException e) {

e.printStackTrace();

        }

}

}

四、总结

        无论你使用HttpPost还是PostMethod,只要上传多个文件ContentType的类型必须分开设置不能笼统的设置成MULTIPART_FORM_DATA

你可能感兴趣的:(后端构造post请求,调用上传图片、pdf文件的外部接口)