赞
踩
在工作上遇到这样一个需求,就是调用我们公司的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编码的,目前还在赵原因,在此先做一个记录。后续找到原因会补充在评论下。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。