Java RestTemplate 请求参数字符串中有大括号{}的请求正确方法

时间:2021-04-12 11:42:34   收藏:0   阅读:0

1 前言

腾讯IM发送离线消息,总是会提示参数中json数据不正确的错误,然而内容json格式是正确。原因是RestTemplate请求get,post的方法没使用正确导致。此文章记录一下。

2 代码

  //参数中字符串中没有含有{}
  //样例:{"MsgRandom":407056434,"SyncOtherMachine":2,"MsgLifeTime":2592000,"OfflinePushInfo":{"Ext":"ext内容","Desc":"测试样例2021-04-10"}
   public static JSONObject post(String url, JSONObject postData) {

        LogUtils.print("info", "url", postData);

        JSONObject json = restTemplate.postForEntity(url, postData, JSONObject.class).getBody();

        return json;
    }



    public static String get(String url) {
        ResponseEntity<String> responseEntity = restTemplate.getForEntity(url, String.class);
        return responseEntity.getBody();
    }

  
//参数中字符串中含有{}
//样例:{"MsgRandom":407056434,"SyncOtherMachine":2,"MsgLifeTime":2592000,"OfflinePushInfo":{"Ext":"{\"id\":\"1377284502649556993\",\"type\":\"1\"}","Desc":"测试样例2021-04-10"}
    public static String getUrlWithParams(String url, Map<String, String> params) {
        ResponseEntity<String> responseEntity = restTemplate.getForEntity(url, String.class, params);
        return responseEntity.getBody();
    }

    public static JSONObject postUrlWithParams(String url, JSONObject params) {

        MediaType type = MediaType.parseMediaType("application/json");
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(type);
        HttpEntity<String> formEntity = new HttpEntity<>(params.toString(), headers);
        ResponseEntity<JSONObject> responsebody = restTemplate.exchange(url, HttpMethod.POST, formEntity, JSONObject.class);

        return responsebody.getBody();
    }

3 小结

实践出真理

评论(0
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!