RestTemplate 發送 get 請求使用誤區 多值為null


http://blog.csdn.net/zhousenshan/article/details/71055687

*****************************************************

首先看一下官方文檔是怎么描述的,傳遞多個值的情況(注意例子中用到的@pathParam,一般要用@queryParam)

 

RestTemplate 實例

guration
public class RestConfiguration {

    @Bean
    @ConditionalOnMissingBean({RestOperations.class, RestTemplate.class})
    public RestOperations restOperations() {
        SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
        requestFactory.setReadTimeout(5000);
        requestFactory.setConnectTimeout(5000);

        RestTemplate restTemplate = new RestTemplate(requestFactory);

        // 使用 utf-8 編碼集的 conver 替換默認的 conver(默認的 string conver 的編碼集為 "ISO-8859-1")
        List<HttpMessageConverter<?>> messageConverters = restTemplate.getMessageConverters();
        Iterator<HttpMessageConverter<?>> iterator = messageConverters.iterator();
        while (iterator.hasNext()) {
            HttpMessageConverter<?> converter = iterator.next();
            if (converter instanceof StringHttpMessageConverter) {
                iterator.remove();
            }
        }
        messageConverters.add(new StringHttpMessageConverter(Charset.forName("UTF-8")));

        return restTemplate;

請求地址

get 請求 url 為

/localhost:8080/test/sendSms?phone=手機號&msg=短信內容

錯誤使用

ired
private RestOperations restOperations;

public void test() throws Exception{
    String url = "http://localhost:8080/test/sendSms";

    Map<String, Object> uriVariables = new HashMap<String, Object>();
    uriVariables.put("phone", "151xxxxxxxx");
    uriVariables.put("msg", "測試短信內容");

    String result = restOperations.getForObject(url, String.class, uriVariables);

服務器接收的時候你會發現,接收的該請求時沒有參數的


正確使用

ired
private RestOperations restOperations;

public void test() throws Exception{
    String url = "http://localhost:8080/test/sendSms?phone={phone}&msg={phone}";

    Map<String, Object> uriVariables = new HashMap<String, Object>();
    uriVariables.put("phone", "151xxxxxxxx");
    uriVariables.put("msg", "測試短信內容");

    String result = restOperations.getForObject(url, String.class, uriVariables);

等價於

ired
private RestOperations restOperations;

public void test() throws Exception{
    String url = "http://localhost:8080/test/sendSms?phone={phone}&msg={phone}";

    String result = restOperations.getForObject(url, String.class,  "151xxxxxxxx", "測試短信內容");

 


免責聲明!

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



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