restTemplate
程序员文章站
2022-03-02 17:35:19
...
@Bean
public RestTemplate createRestTemplate() {
OkHttpClient okHttpClient = new OkHttpClient.Builder()
.writeTimeout(10, TimeUnit.SECONDS)
.readTimeout(10, TimeUnit.SECONDS)
.connectTimeout(10, TimeUnit.SECONDS)
.build();
return new RestTemplate(new OkHttp3ClientHttpRequestFactory(okHttpClient));
}
https://*.com/questions/4526273/what-does-enctype-multipart-form-data-mean
https://www.baeldung.com/spring-rest-template-multipart-upload
org.springframework.web.client.HttpClientErrorException$BadRequest: 400 Bad Request
restTemplate的bug, 当post contentType是multipart/form-data
restTemplate有问题
/*try {
//header
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.MULTIPART_FORM_DATA);
//body
LinkedMultiValueMap<String, Object> body = new LinkedMultiValueMap<>();
body.add("api_key", publicKey);
body.add("api_secret", privateKey);
body.add("image", Base64.decodeBase64(idCardPositive));
// httpEntity
HttpEntity<LinkedMultiValueMap<String, Object>> httpEntity = new HttpEntity<>(body, headers);
String url = FaceUtils.getUrl(baseUrl, Constant.ocridCard);
ResponseEntity<FaceOCRVerifyResp> entity = restTemplate.postForEntity(url, httpEntity, FaceOCRVerifyResp.class);
if (entity.getBody() != null) {
return entity.getBody();
}
} catch (RestClientException e) {
e.printStackTrace();
}
return null;*/
try {
RequestBody requestBody = new MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart("api_key", publicKey)
.addFormDataPart("api_secret", privateKey)
.addFormDataPart("image", "image.png",
RequestBody.create(okhttp3.MediaType.parse(MediaType.IMAGE_PNG_VALUE), Base64.decodeBase64(idCardPositive)))
.build();
Request request = new Request.Builder()
.url(FaceUtils.getUrl(baseUrl, Constant.ocridCard))
.post(requestBody)
.build();
Response response = okHttpClient.newCall(request).execute();
String body = response.body().string();
logger.info("face++ ocr body >>> {} ", body);
//status code
int code = response.code();
if (response.isSuccessful()) {
return JSON.parseObject(body, FaceOCRVerifyResp.class);
}
} catch (IOException e) {
logger.error("face++ ocr exception >>> {}", e.getMessage());
}
上一篇: mongodb的安装和开机自启动详细讲解
下一篇: 关于使用Redisson订阅数问题
推荐阅读
-
Spring Boot使用RestTemplate消费REST服务的几个问题记录
-
Spring cloud restTemplate 传递复杂参数的方式(多个对象)
-
Spring Boot使用RestTemplate消费REST服务的几个问题记录
-
详解SpringBoot通过restTemplate实现消费服务
-
Spring cloud restTemplate 传递复杂参数的方式(多个对象)
-
Spring RestTemplate具体使用详解
-
详解SpringBoot通过restTemplate实现消费服务
-
基于RestTemplate的使用方法(详解)
-
基于RestTemplate的使用方法(详解)
-
Eureka restTemplate访问超时