环境搭建web
本文环境指的 Spring Boot下1.4.2版本下
pom.xml (核心内容)spring
<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包json
RestTemplate有简写方法,但不具有通用性且没法作细节设置故本文再也不赘述
举例:浏览器
restTemplate.getForObject(url, String.class);
// 向url发送 Get类型请求,将返回结果 以String类型显示
// 能很明显发现没法设置编码格式等,乱码等问题没法解决
1
2
3
有兴趣可访问,下文只提通用性方法
RestTemplate 官方 APIapp
注意异步
默认的 RestTemplate 有个机制是请求状态码非200 就抛出异常,会中断接下来的操做,若是要排除这个问题那么须要覆盖默认的 ResponseErrorHandler ,下面为用什么也不干覆盖默认处理机制ide
RestTemplate restTemplate = new RestTemplate();
ResponseErrorHandler responseErrorHandler = new ResponseErrorHandler() {
@Override
public boolean hasError(ClientHttpResponse clientHttpResponse) throws IOException {
return true;
}spring-boot
@Override
public void handleError(ClientHttpResponse clientHttpResponse) throws IOException {post
}
};
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 版权声明:本文为博主原创文章,转载请附上博文连接!