关于springboot restTemplate传文件爬坑

1.关于restTemplate post请求中包含文件类型 

public void test5(){
    MultiValueMap param = new LinkedMultiValueMap();
    
    FileSystemResource  file = new FileSystemResource("C:\\Users\\Ryan\\Postman\\files\\zm.png");
    param .add("image",file);
    ResponseEntity<String> idCardOcrRes = this.restTemplateForFile(idCardOCRUrl,param,String.class);
    String idCardOcrResBody = idCardOcrRes.getBody();
    System.out.println(idCardOcrResBody);
}

private <T> ResponseEntity<T> restTemplateForFile(String url, MultiValueMap<String,Object> map, Class<T> responseClass){
    //设置请求头
    HttpHeaders headers = new HttpHeaders();
    MediaType mediaType = MediaType.parseMediaType("multipart/form-data");
    headers.setContentType(mediaType);

    //请求体为入参map

    //用httpEntity封装整个请求报文
    HttpEntity<MultiValueMap<String,Object>> entity = new HttpEntity(map,headers);

    ResponseEntity<T> responseEntity = restTemplate.postForEntity(url, entity, responseClass);
    return responseEntity;
}

注意使用FileSystemResource类型的文件即可。

本人在过程中遇到过一个问题,在此记录下来,param为MultiValueMap

logger.info("param:{},userNo:{},incomingNo:{}",JSONObject.toJSONString(param),userNo,incomingNo);

若加入此日志输出,会清空新建的文件,这个问题困扰好久!!!

 

2.关于restTemplate 响应状态码捕捉

捕捉  RestClientResponseException e 类型异常,

int statis = e.getRawStatusCode();
String responseBodyAsString = e.getResponseBodyAsString();

可以得到具体的响应消息以及响应状态码

 

 

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值