什么是RestTemplate?
RestTemplate默认是使用SimpleClientHttpRequestFactory,内部是调用jdk的HttpConnection,默认超时为-1
基于jdk的spring的RestTemplate
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd" default-autowire="byName" default-lazy-init="true"> <!--方式一、使用jdk的实现--> <bean id="ky.requestFactory" class="org.springframework.http.client.SimpleClientHttpRequestFactory"> <property name="readTimeout" value="10000"/> <property name="connectTimeout" value="5000"/> </bean> <bean id="simpleRestTemplate" class="org.springframework.web.client.RestTemplate"> <constructor-arg ref="ky.requestFactory"/> <property name="messageConverters"> <list> <bean class="org.springframework.http.converter.FormHttpMessageConverter"/> <bean class="org.springframework.http.converter.xml.MappingJackson2XmlHttpMessageConverter"/> <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"/> <bean class="org.springframework.http.converter.StringHttpMessageConverter"> <property name="supportedMediaTypes"> <list> <value>text/plain;charset=UTF-8</value> </list> </property> </bean> </list> </property> </bean> </beans>
使用Httpclient连接池的方式(推荐)
<!--使用httpclient的实现,带连接池--> <!--在httpclient4.3版本后才有--> <bean id="httpClientBuilder" class="org.apache.http.impl.client.HttpClientBuilder" factory-method="create"> <property name="connectionManager"> <bean class="org.apache.http.impl.conn.PoolingHttpClientConnectionManager"> <!--整个连接池的并发--> <property name="maxTotal" value="50"/> <!--每个主机的并发--> <property name="defaultMaxPerRoute" value="50"/> </bean> </property> <!--开启重试--> <property name="retryHandler"> <bean class="org.apache.http.impl.client.DefaultHttpRequestRetryHandler"> <constructor-arg value="2"/> <constructor-arg value="true"/> </bean> </property> <property name="defaultHeaders"> <list> <bean class="org.apache.http.message.BasicHeader"> <constructor-arg value="Content-Type"/> <constructor-arg value="text/html;charset=UTF-8"/> </bean> <bean class="org.apache.http.message.BasicHeader"> <constructor-arg value="Accept-Encoding"/> <constructor-arg value="gzip,deflate"/> </bean> <bean class="org.apache.http.message.BasicHeader"> <constructor-arg value="Accept-Language"/> <constructor-arg value="zh-CN"/> </bean> </list> </property> </bean> <bean id="httpClient" factory-bean="httpClientBuilder" factory-method="build"/> <bean id="restTemplate" class="org.springframework.web.client.RestTemplate"> <property name="messageConverters"> <list value-type="org.springframework.http.converter.HttpMessageConverter"> <bean class="org.springframework.http.converter.StringHttpMessageConverter"> <property name="supportedMediaTypes"> <value>text/html;charset=UTF-8</value> </property> </bean> <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"> <property name="supportedMediaTypes"> <value>application/json;charset=UTF-8</value> </property> </bean> <bean class="org.springframework.http.converter.ResourceHttpMessageConverter"/> <bean class="org.springframework.http.converter.support.AllEncompassingFormHttpMessageConverter"/> <bean class="org.springframework.http.converter.FormHttpMessageConverter"/> <bean class="org.springframework.http.converter.xml.MappingJackson2XmlHttpMessageConverter"/> </list> </property> <property name="requestFactory"> <bean class="org.springframework.http.client.HttpComponentsClientHttpRequestFactory"> <constructor-arg ref="httpClient"/> <!--连接时间(毫秒)--> <property name="connectTimeout" value="20000"/> <!--读取时间(毫秒)--> <property name="readTimeout" value="20000"/> </bean> </property> </bean>
初体验(POST)
package com.winner.rest; import com.alibaba.fastjson.JSON; import org.springframework.beans.factory.annotation.Value; import org.springframework.http.HttpEntity; import org.springframework.http.HttpHeaders; import org.springframework.http.MediaType; import org.springframework.stereotype.Service; import org.springframework.web.client.RestTemplate; import javax.annotation.Resource; import java.io.UnsupportedEncodingException; /** * Created by winner_0715 on 2017/1/7. */ @Service public class TestGet { @Resource private RestTemplate restTemplate; /** * 要请求的url,一般放在配置文件中 */ @Value(value = "@{remote.url}") private String remoteUrl; public String postRemoteData(ParameterRo ro) throws UnsupportedEncodingException { /** * 设置请求头 */ HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.parseMediaType("application/json;charset=UTF-8")); headers.add("Accept", MediaType.APPLICATION_JSON.toString()); /** * POST请求参数,根据需要进行封装 */ String bodyData = new String(Base64Util.encodeData(JSON.toJSONString(ro)).getBytes("UTF-8"), "UTF-8"); /** * 查看HttpEntity的构造方法,包含只有请求头和只有请求体的情况 */ HttpEntity<String> httpEntity = new HttpEntity<String>(bodyData, headers); /** * 执行操作 */ String result = restTemplate.postForObject(remoteUrl, httpEntity, String.class); return result; } /** * 模拟请求参数 */ private class ParameterRo { private Integer id = 123; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } } }
初体验(GET)
package com.winner.rest; import com.alibaba.fastjson.JSON; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Service; import org.springframework.web.client.RestTemplate; import javax.annotation.Resource; import java.io.UnsupportedEncodingException; /** * Created by winner_0715 on 2017/1/7. */ @Service public class TestGet { @Resource private RestTemplate restTemplate; /** * 要请求的url,一般放在配置文件中 */ @Value(value = "@{remote.url}") private String remoteUrl; public String getRemoteData(ParameterRo ro) throws UnsupportedEncodingException { //根据需要也可以设置请求头 /** * get请求参数,根据需要进行封装(加密等) */ String getData = new String(Base64Util.encodeData(JSON.toJSONString(ro)).getBytes("UTF-8"), "UTF-8"); /** * 执行操作 */ String result = restTemplate.getForObject(remoteUrl + "?" + getData, String.class); return result; } /** * 模拟请求参数 */ private class ParameterRo { private Integer id = 123; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } } }