本文共 2279 字,大约阅读时间需要 7 分钟。
手动实例化,这个我基本不用
RestTemplate restTemplate = new RestTemplate();
依赖注入,通常情况下我使用 java.net 包下的类构建的 SimpleClientHttpRequestFactory
@Configurationpublic 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> messageConverters = restTemplate.getMessageConverters(); Iterator > 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=短信内容
@Autowiredprivate RestOperations restOperations;public void test() throws Exception{ String url = "http://localhost:8080/test/sendSms"; MapuriVariables = new HashMap (); uriVariables.put("phone", "151xxxxxxxx"); uriVariables.put("msg", "测试短信内容"); String result = restOperations.getForObject(url, String.class, uriVariables);}
服务器接收的时候你会发现,接收的该请求时没有参数的
@Autowiredprivate RestOperations restOperations;public void test() throws Exception{ String url = "http://localhost:8080/test/sendSms?phone={phone}&msg={phone}"; MapuriVariables = new HashMap (); uriVariables.put("phone", "151xxxxxxxx"); uriVariables.put("msg", "测试短信内容"); String result = restOperations.getForObject(url, String.class, uriVariables);}
等价于
@Autowiredprivate 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", "测试短信内容");}
转载地址:http://uvhkl.baihongyu.com/