RestTemplate 發送 get 請求使用誤區 多個參數傳值爲null(轉載)

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

RestTemplate 實例

@Configuration
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 爲服務器

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

 


錯誤使用

@Autowired
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);
}

 

 

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


正確使用

@Autowired
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);
}

 

等價於編碼

@Autowired
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", "測試短信內容");
}
相關文章
相關標籤/搜索