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 @ 2023-04-27 10:11  mingruqi  阅读(208)  评论(0编辑  收藏  举报