RestTemplate时出现RestClientException原因和解决方法

RestTemplate时出现RestClientException的解决办法

1.先来看一下报错吧

 2.我的写法

Map<String, Object> params = paramRequest();
        params.put("unionId", unionId);
        params.put("userId", userId);
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        HttpEntity<Map<String, Object>> requestEntity = new HttpEntity<>(params, httpHeaders);
        JSONObject stoResult = restTemplate.postForObject(userCenterUrl + BIND, requestEntity, JSONObject.class);

3.对方的接口要求的ContentType是APPLICATION_FORM_URLENCODED,表单提交但是HttpEntity中用map、hashmap 都报错,都不可以。
只有改成multivalueMap才可以。如下:

复制代码
String timestamp = SDF.format(new Date());
        MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
        params.add("timestamp", timestamp);
        params.add("sign", SignUtils.signRequest(timestamp, baseAppsecret));
        params.add("appKey", baseAppkey);
        params.add("unionId", unionId);
        params.add("userId", userId);
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        HttpEntity<MultiValueMap<String, String>> requestEntity = new HttpEntity<>(params, httpHeaders);
        JSONObject stoResult = restTemplate.postForObject(userCenterUrl + BIND, requestEntity, JSONObject.class);
复制代码

4.原因:是在doExecute方法中的 requestCallback.doWithRequest();方法中出现的错误

 ** requestCallback.doWithRequest()的相关源码:然后就是在我圈出来的地方报的错。
大概的原因是因为Content-Type 的类型和map 、hashmap 请求的参数类型不匹配。**

 

posted @   mingruqi  阅读(297)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· 单线程的Redis速度为什么快?
· 展开说说关于C#中ORM框架的用法!
· Pantheons:用 TypeScript 打造主流大模型对话的一站式集成库
历史上的今天:
2021-04-27 C#调用DLL的几种方法
2019-04-27 Groovy Closure简介
2019-04-27 一次搞懂----模块化、组件化、插件化和热修复
点击右上角即可分享
微信分享提示