java实现调用第三方接口post请求上传文件请求参数为MultipartFile携带token的解决方案

java实现调用第三方接口post请求上传文件请求参数为MultipartFile携带token的解决方案

控制器层:

 /**
     * 上传名片
     *
     * @param file 文件流
     * @return 返回结果
     */
    @PostMapping("/upload_image")
    public AjaxResult uploadImage(@RequestParam("file") MultipartFile file) {
        return iApiUserCenterService.uploadImage(file);
    }
    ```
    **serviceimpl:**
    /**
     * 上传名片
     */
    @Override
    public AjaxResult uploadImage(MultipartFile file) {
        AjaxResult ajaxResult = new AjaxResult();

        try {
            MultiValueMap<String, Object> bodyMap = new LinkedMultiValueMap<>();
            bodyMap.add("file", new FileSystemResource(convert(file)));


            String url = this.url + "/image/upload";
            String res = httpPostUtils.JPost(url,file,httpSession.getAttribute("token").toString());
            if ("".equals(res) || res == null) {
                logger.info("上传名片失败,调用官网接口返回结果为空->{}", res);
                ajaxResult.put(AjaxResult.CODE_TAG, AjaxResult.Type.ERROR);
                ajaxResult.put(AjaxResult.MSG_TAG, "上传名片失败,调用官网接口返回结果为空");
                return ajaxResult;
            }
            //将返回数据转换成json
            JSONObject jsonObject = JSONObject.parseObject(res);
            String message = (jsonObject.get("msg")).toString();
            String code = (jsonObject.get("code")).toString();
            JSONObject dataObject = (JSONObject) jsonObject.get("data");
            String path = dataObject.getString("path");
            //TODO 需要将返回的图片路径进行保存
            if ("1".equals(code)) {
                ajaxResult.put(AjaxResult.CODE_TAG, AjaxResult.Type.SUCCESS);
                ajaxResult.put(AjaxResult.MSG_TAG, message);
                ajaxResult.put(AjaxResult.DATA_TAG, path);
            } else {
                ajaxResult.put(AjaxResult.CODE_TAG, AjaxResult.Type.ERROR);
                ajaxResult.put(AjaxResult.MSG_TAG, message);
            }
            logger.info("上传名片接口调用结束结束,响应结果{}", res);


        } catch (Exception e) {
            ajaxResult.put(AjaxResult.CODE_TAG, AjaxResult.Type.ERROR);
            ajaxResult.put(AjaxResult.MSG_TAG, "调用上传名片接口异常");
            logger.info("调用上传名片接口异常,错误信息{}", e.getMessage());
        }
        return ajaxResult;
    }


## 重要的util
 /**
     *
     *  发送文件MultipartFile类型的参数请求第三方接口
     * @param url  请求url
     * @param file 参数
     * @return 字符流
     * @throws IOException
     */
    public String JPost(String url, MultipartFile file, String token) throws IOException {
        MultiValueMap<String, Object> bodyMap = new LinkedMultiValueMap<>();
        bodyMap.add("file", new FileSystemResource(convert(file)));
        HttpHeaders headers = new HttpHeaders();
        headers.add("accept", "*/*");
        headers.add("connection", "Keep-Alive");
        headers.add("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
        headers.add("Accept-Charset", "utf-8");
        headers.add("Content-Type", "application/json; charset=utf-8");
        headers.add("token", token);
        headers.setContentType(MediaType.MULTIPART_FORM_DATA);
        HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<>(bodyMap, headers);
        RestTemplate restTemplate = new RestTemplate();
        ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.POST, requestEntity, String.class);
        String body = response.getBody();
        return body;
    }

    /**
     * 接收处理传过来的文件
     * @param file MultipartFile 类型的文件
     * @return
     */
    public static File convert(MultipartFile file) {
        File convFile = new File(file.getOriginalFilename());
        try {
            convFile.createNewFile();
            FileOutputStream fos = new FileOutputStream(convFile);
            fos.write(file.getBytes());
            fos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return convFile;
    }


以上成功解决调用第三方接口上传文件问题,但是会在根目录下创建一个文件需要重新回调删除有待解决


  • 4
    点赞
  • 25
    收藏
    觉得还不错? 一键收藏
  • 9
    评论
java后端调用第三方接口携带文件参数解决方案是使用MultipartFile携带文件参数。您可以使用以下步骤来实现: 1. 导入所需的依赖项,包括spring-boot-starter-web和spring-boot-starter-websocket。 2. 在您的Controller类中创建一个POST请求的处理方法。在该方法中,将MultipartFile参数添加到方法的参数列表中,以接收文件。 3. 使用RestTemplate或者HttpClient等HTTP客户端库创建一个HTTP请求。 4. 将文件转换为字节数组,并将其添加到请求体中。确保您设置正确的Content-Type头部。 5. 如果需要,您还可以添加其他请求参数,例如token。 6. 发送请求并获取响应。 以下是一个简单的示例代码片段,演示了如何使用MultipartFile发送文件参数POST请求: ```java @PostMapping("/upload") public String uploadFile(@RequestParam("file") MultipartFile file, @RequestParam("token") String token) { RestTemplate restTemplate = new RestTemplate(); String url = "https://api.example.com/upload"; // 将文件转换为字节数组,并设置Content-Type头部 HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_OCTET_STREAM); byte[] fileBytes; try { fileBytes = file.getBytes(); } catch (IOException e) { // 处理文件读取错误 return "文件读取错误"; } // 创建请求体 HttpEntity<byte[]> requestEntity = new HttpEntity<>(fileBytes, headers); // 添加其他请求参数,例如token MultiValueMap<String, String> requestBody = new LinkedMultiValueMap<>(); requestBody.add("token", token); // 发送请求 ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.POST, requestEntity, String.class, requestBody); // 处理响应 if (response.getStatusCode() == HttpStatus.OK) { return "文件上传成功"; } else { return "文件上传失败"; } } ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 9
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值