Spring框架中发送http请求--RestTemplate

环境搭建

本文环境指的 Spring Boot下1.4.2版本下 
pom.xml (核心内容)

 <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.4.2.RELEASE</version>
        <relativePath/>
</parent>
    <dependencies>
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependencies>
1
2
3
4
5
6
7
8
9
10
11
12
如果单纯想用RestTemplate 引上面的应该是多余了,博主没去查阅具体那个包,可以自行去Maven 中央仓库搜索有没有专门的RestTemplate包

RestTemplate有简写方法,但不具备通用性且无法做细节设置故本文不再赘述 
举例:

restTemplate.getForObject(url, String.class);
// 向url发送 Get类型请求,将返回结果 以String类型显示
// 能很明显发现无法设置编码格式等,乱码等问题无法解决
1
2
3
有兴趣可访问,下文只提通用性方法 
RestTemplate 官方 API

注意

默认的 RestTemplate 有个机制是请求状态码非200 就抛出异常,会中断接下来的操作,如果要排除这个问题那么需要覆盖默认的 ResponseErrorHandler ,下面为用什么也不干覆盖默认处理机制

        RestTemplate restTemplate = new RestTemplate();
        ResponseErrorHandler responseErrorHandler = new ResponseErrorHandler() {
            @Override
            public boolean hasError(ClientHttpResponse clientHttpResponse) throws IOException {
                return true;
            }

            @Override
            public void handleError(ClientHttpResponse clientHttpResponse) throws IOException {

            }
        };
        restTemplate.setErrorHandler(responseErrorHandler);
1
2
3
4
5
6
7
8
9
10
11
12
13
实例

application/json类型请求
RestTemplate restTemplate=new RestTemplate();
String url="http://www.testXXX.com";
/* 注意:必须 http、https……开头,不然报错,浏览器地址栏不加 http 之类不出错是因为浏览器自动帮你补全了 */
HttpHeaders headers = new HttpHeaders();
/* 这个对象有add()方法,可往请求头存入信息 */       
headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
/* 解决中文乱码的关键 , 还有更深层次的问题 关系到 StringHttpMessageConverter,先占位,以后补全*/ 
HttpEntity<String> entity = new HttpEntity<String>(body, headers);
/* body是Http消息体例如json串 */ 
restTemplate.exchange(url, HttpMethod.POST, entity, String.class);
/*上面这句返回的是往 url发送 post请求 请求携带信息为entity时返回的结果信息
String.class 是可以修改的,其实本质上就是在指定反序列化对象类型,这取决于你要怎么解析请求返回的参数*/
1
2
3
4
5
6
7
8
9
10
11
12
另post、get、delete……等其他http请求类型只需将exchange参数修改为HttpMethod.GET 等等。

application/x-www-form-urlencoded类型请求
        RestTemplate restTemplate=new RestTemplate();
        /* 注意:必须 http、https……开头,不然报错,浏览器地址栏不加 http 之类不出错是因为浏览器自动帮你补全了 */
        String url="http://www.testXXX.com";
        String bodyValTemplate = "var1=" + URLEncoder.encode("测试数据1", "utf-8") + "&var2=" + URLEncoder.encode("test var2", "utf-8");
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        HttpEntity entity = new HttpEntity(bodyValTemplate, headers);
        restTemplate.exchange(url, HttpMethod.POST, entity, String.class);
1
2
3
4
5
6
7
8
9
另一种构造 HttpEntity 的方法

        LinkedMultiValueMap body=new LinkedMultiValueMap();
        body.add("var1","测试数据1");
        body.add("var2","test Val2");
        HttpEntity entity = new HttpEntity(body, headers);
1
2
3
4
上方请求在PostMan里等效于图 


RestTemplate还有专门支持异步请求的特殊类 AsyncRestTemplate,具体用法和RestTemplate类似(需要 ListenableFutureCallback 基础)
--------------------- 
作者:SolidCocoi 
来源:CSDN 
原文:https://blog.csdn.net/u014430366/article/details/65633679?utm_source=copy 
版权声明:本文为博主原创文章,转载请附上博文链接!

转载于:https://my.oschina.net/newchaos/blog/2247747

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值