1. 程式人生 > >RestTemplate 發送 get 請求使用誤區 多個參數傳值為null(轉載)

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

pretty b2c shm put xxxxx ont log 手機號 col

首先看一下官方文檔是怎麽描述的,傳遞多個值的情況(註意例子中用到的@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", "測試短信內容");
}

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