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

2021-06-05 00:02

阅读:744

标签:string   method   请求   and   ons   inf   cat   ati   push   

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 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 params) {
        ResponseEntity 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 formEntity = new HttpEntity(params.toString(), headers);
        ResponseEntity responsebody = restTemplate.exchange(url, HttpMethod.POST, formEntity, JSONObject.class);

        return responsebody.getBody();
    }

3 小结

实践出真理

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

标签:string   method   请求   and   ons   inf   cat   ati   push   

原文地址:https://www.cnblogs.com/fanbi/p/14640474.html


评论


亲,登录后才可以留言!