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 请求的参数类型不匹配。**
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· 单线程的Redis速度为什么快?
· 展开说说关于C#中ORM框架的用法!
· Pantheons:用 TypeScript 打造主流大模型对话的一站式集成库
2021-04-27 C#调用DLL的几种方法
2019-04-27 Groovy Closure简介
2019-04-27 一次搞懂----模块化、组件化、插件化和热修复