RestTemplate常用的get和post帶參數請求


在RestTemplate提供的方法中,有一個參數就是目標URL,參數是跟在后面的一個數量可變參數,但是在這里就有個問題,這個方法怎么知道我傳的參數值是對應在目標接口的哪個參數的呢:

public <T> T postForObject(String url, Object request, Class<T> responseType, Object... uriVariables)

  比如有個url的鏈接是post方式請求,然后需要提供name和id兩個參數,返回值是一個json,然后調用:

JSONObject result = restTemplate.postForObject(url, null, JSONObject.class, "張三", "2");


這里就無法分辨張三是name還是2是name。所以post一般是把參數封裝到request里面。

JSONObject msg = new JSONObject();
        msg.put("key", "@*2y9$jl");
        msg.put("receiver", receiverEcommerceId);
        msg.put("title", title);
        msg.put("content", content);
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        HttpEntity request = new HttpEntity(msg.toJSONString(), headers);
JSONObject result = restTemplate.postForObject(url, request, JSONObject.class);

get方式帶參數:

String url=http://test.com/url?param1={param1}&param2={param2};
Map<String, Object> params = new HashMap<>();
params.put("param1", "value1");
params.put("param2", "value2");
JSONObject mutiData = restTemplate.getForObject(url, JSONObject.class, params);

值得一提的是,如果是把url配置在properties配置文件里面的,sax解析會出錯,得把&替換成&amp;


免責聲明!

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



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