JAVA调用第三方上传接口

本文介绍了一种解决方案,前端通过阿里OSS上传文件,然后传递给后端URL,避免了多服务间文件流传输的问题。重点讲解了如何使用FileUrlResource简化上传流程并调用第三方接口的过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

遇到一个需求,需要把文件传给第三方,调用顺序是这样的,前端->A服务->B服务->第三方接口,如果通过文件流在多个服务之间传输,肯定会带来性能问题。最终解决办法是:前端直传阿里OSS,然后传给后端URL,多个服务之间传递URL, 在B服务中,根据URL请求第三方接口。
1. 根据URL下载到本地,再用本地文件上传第三方接口。
2. 直接用FileUrlResource fileUrlResource = new FileUrlResource(new URL(fileUrl));这种方式更简洁,再放到MultiValueMap中。



@Override
public ZlResponse<ZlResult> uploadContractFile(String sourceSystem, String sourceDocumentNumber, String fileUrl) {
    log.info("上传合同文件调用甄零第三方接口开始");
    Map<String, Object> params = new HashMap<>();
    params.put("fileType", "DOCUMENT");
    params.put("sourceSystem", sourceSystem);
    params.put("sourceDocumentNumber", sourceDocumentNumber);

    // 截取文件名
    String fileName = fileUrl.substring(fileUrl.lastIndexOf("/") + 1);
    params.put("fileName", fileName);

    try {
        FileUrlResource fileUrlResource = new FileUrlResource(new URL(fileUrl));
        params.put("file", fileUrlResource);
    } catch (IOException e) {
        e.printStackTrace();
    }

    String response = this.invokeMultipartFormData(DOMAIN + UPLOAD_FILE_URL, params, String.class);
    return JSON.parseObject(response, new TypeReference<ZlResponse<ZlResult>>() {
    });
}
@SuppressWarnings("unchecked")
private static <T> T invoke(HttpMethod httpMethod, String url, Map params, Map<String, String> headers, Class<T> cls) {
    headers.put("Content-Type", MediaType.MULTIPART_FORM_DATA_VALUE);

    MultiValueMap xMap = new LinkedMultiValueMap();
    xMap.setAll(params);
    HttpHeaders httpHeaders = new HttpHeaders();
    httpHeaders.setAll(headers);

    HttpEntity<MultiValueMap<String, String>> httpEntity = new HttpEntity<>(xMap, httpHeaders);
    try {
        ResponseEntity<T> responseEntity = restTemplate.exchange(url, httpMethod, httpEntity, cls, params);
        if (responseEntity.getStatusCode().isError()) {
            return null;
        }
        return responseEntity.getBody();
    } catch (Exception e) {
        return restTemplateErrorMsg(e);
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值