RestTemplate发送请求携带文件

        在工作上遇到这样一个需求,就是调用我们公司的AI平台,将图片文件发送给他们,他们进行解析然后返回解析结果。

        首先用python进行调用一次,发送捕获的接口是这样的:

 那么用java代码该如何组装这个请求发送过去呢?

 public static<T> String sendPostWithFile(String url, Map<String,String> head, Map<String,T> body, File file) throws IOException {
        HttpHeaders requestHeaders = new HttpHeaders();
        requestHeaders.setAcceptCharset(Arrays.asList(Charset.forName("UTF-8")));
        head.forEach((k,v)->{
            requestHeaders.add(k,v);
        });
        requestHeaders.setContentType(MediaType.MULTIPART_FORM_DATA);

        MultiValueMap<String, Object> params = new LinkedMultiValueMap<>();
        body.forEach((k,v)->{
            params.add(k,v);
        });
        if(file != null && file.exists()){
            MultiValueMap<String, String> fileMap = new LinkedMultiValueMap<>();
            ContentDisposition contentDisposition = ContentDisposition
                    .builder("form-data")
                    .name(file.getPath())
                    .filename(file.getName())
                    .build();
            fileMap.add(HttpHeaders.CONTENT_DISPOSITION,contentDisposition.toString());
            byte[] fileContent = readContentIntoByteArray(file); //获取文件的字节流
            HttpEntity<byte[]> fileEntity = new HttpEntity<>(fileContent, fileMap);
            params.add(contentDisposition.toString(),fileEntity);
        }

        HttpEntity<MultiValueMap<String, Object>> httpEntity = new HttpEntity<>(params, requestHeaders);

        HttpComponentsClientHttpRequestFactory httpRequestFactory = new HttpComponentsClientHttpRequestFactory();
        httpRequestFactory.setConnectionRequestTimeout(30000);
        httpRequestFactory.setConnectTimeout(30000);
        httpRequestFactory.setReadTimeout(30000);

        RestTemplate restTemplate = new RestTemplate(httpRequestFactory);
        List<HttpMessageConverter<?>> converters = restTemplate.getMessageConverters();
        converters.removeIf(httpMessageConverter -> httpMessageConverter instanceof StringHttpMessageConverter);
        converters.add(0, new StringHttpMessageConverter(StandardCharsets.UTF_8));

        String res = restTemplate.postForObject(url, httpEntity, String.class);
        log.info("请求返回结果:"+res);
        return res;
    }

1.设置请求头,并且设置ContentType为multipart/form-data形式的。

2.组装请求体。

3.将文件处理好后,增加到请求体中。

4.发送请求。

这里有一个问题就是,我调用的这个接口返回的中文是unicode编码的,目前还在赵原因,在此先做一个记录。后续找到原因会补充在评论下。

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
您可以使用`RestTemplate`发送带有文件的POST请求。以下是一个示例: ```java import org.springframework.core.io.FileSystemResource; import org.springframework.http.HttpEntity; import org.springframework.http.HttpHeaders; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.util.LinkedMultiValueMap; import org.springframework.util.MultiValueMap; import org.springframework.web.client.RestTemplate; import java.io.File; public class FileUploadExample { public static void main(String[] args) { String url = "http://example.com/upload"; String filePath = "/path/to/file.txt"; RestTemplate restTemplate = new RestTemplate(); // 设置请求头 HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.MULTIPART_FORM_DATA); // 构建请求体 MultiValueMap<String, Object> body = new LinkedMultiValueMap<>(); body.add("file", new FileSystemResource(new File(filePath))); // 构建请求实体 HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<>(body, headers); // 发送请求 ResponseEntity<String> response = restTemplate.postForEntity(url, requestEntity, String.class); // 处理响应 if (response.getStatusCode().is2xxSuccessful()) { System.out.println("文件上传成功"); } else { System.out.println("文件上传失败"); } } } ``` 在上述示例中,您需要设置正确的URL和文件路径。通过将文件包装在`FileSystemResource`中,并将其添加到`MultiValueMap`中,您可以将文件作为Multipart形式的请求发送到服务器。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值