spring boot RestTemplate 发送 get 请求使用误区

闲话少说,代码说话

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", "测试短信内容");
}
  • 5
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值