閒話少說,代碼說話
RestTemplate 實例
手動實例化,這個我基本不用
RestTemplate restTemplate = new RestTemplate();
依賴注入,通常情況下我使用 java.net 包下的類構建的 SimpleClientHttpRequestFactory
@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", "測試短信內容");
}