Java RestTemplate 請求參數字符串中有大括號{}的請求正確方法


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 小結

實踐出真理


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM