使用RestTemplate封装post请求
之前笔者写过一篇比较实用的文章 java使用httpclient封装post请求和get的请求,其实java中实现http请求还可以用 RestTemplate 完成,下面给出示例代码:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
|
import com.alibaba.fastjson.JSONObject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.http.*; import org.springframework.http.converter.StringHttpMessageConverter; import org.springframework.web.client.RestTemplate; import javax.annotation.PostConstruct; import java.nio.charset.Charset; public class HttpHelper { private static Logger logger = LoggerFactory.getLogger(HttpHelper. class ); private RestTemplate restTemplate; private HttpHeaders httpHeaders; @PostConstruct public void init() { restTemplate = new RestTemplate(); restTemplate.getMessageConverters().add( 0 , new StringHttpMessageConverter(Charset.forName( "UTF-8" ))); httpHeaders = new HttpHeaders(); httpHeaders.setContentType(org.springframework.http.MediaType.APPLICATION_JSON); } /** * post - json * @param params * @return */ public String post(JSONObject params, String url) { logger.info( "请求参数:{}" , params.toJSONString()); ResponseEntity<String> response; try { response = restTemplate.exchange( url, HttpMethod.POST, new HttpEntity<>(params, httpHeaders), String. class ); } catch (Exception e) { logger.error( "请求异常" , e); return "请求异常" ; } logger.info( "响应结果:{}" , JSONObject.toJSONString(response)); if (response.getStatusCode().equals(HttpStatus.OK)) { logger.info( "请求成功,返回结果:{}" , response.getBody()); return response.getBody(); } logger.error( "请求失败,Http状态码:{},返回结果:{}" , response.getStatusCode(), response.getBody()); return response.getBody(); } } |
RestTemplate 是 Spring 提供的用于访问Rest服务的客户端,RestTemplate 提供了多种便捷访问远程Http 服务的方法,能够大大提高客户端的编写效率。
RestTemplate使用封装
之前接口调用习惯性使用HttpClient,代码复杂,冗余代码多,关心资源回收用起来不是很爽。
RestTemplate默认依赖jdk的HTTP连接工具。也可以 通过setRequestFactory属性切换到不同的HTTP源,比如Apache HttpComponents、Netty、OkHttp。
1、SpringBoot使用RestTemplate(使用apache的httpclient)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
|
import org.springframework.boot.web.client.RestTemplateBuilder; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.http.client.ClientHttpRequestFactory; import org.springframework.http.client.HttpComponentsClientHttpRequestFactory; import org.springframework.http.converter.ByteArrayHttpMessageConverter; import org.springframework.http.converter.FormHttpMessageConverter; import org.springframework.http.converter.HttpMessageConverter; import org.springframework.http.converter.ResourceHttpMessageConverter; import org.springframework.http.converter.StringHttpMessageConverter; import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter; import org.springframework.http.converter.support.AllEncompassingFormHttpMessageConverter; import org.springframework.web.client.RestTemplate; import java.nio.charset.Charset; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.List; import java.util.concurrent.TimeUnit; @Configuration public class RestTemplateConfig { @Bean public RestTemplate getRestTemplate() { //手动指定转换器(HttpMessageConverter) List<HttpMessageConverter<?>> messageConverters = new ArrayList<HttpMessageConverter<?>>(); messageConverters.add( new ByteArrayHttpMessageConverter()); messageConverters.add( new StringHttpMessageConverter(Charset.forName( "UTF-8" ))); //string强制使用UTF-8 messageConverters.add( new ResourceHttpMessageConverter()); messageConverters.add( new AllEncompassingFormHttpMessageConverter()); messageConverters.add( new FormHttpMessageConverter()); MappingJackson2HttpMessageConverter jacksonConverter = new MappingJackson2HttpMessageConverter(); jacksonConverter.getObjectMapper().setDateFormat( new SimpleDateFormat( "yyyy-MM-dd HH:mm:ss" )); messageConverters.add(jacksonConverter); RestTemplate restTemplate = new RestTemplateBuilder().additionalMessageConverters(messageConverters).build(); restTemplate.setRequestFactory(getClientHttpRequestFactory()); return restTemplate; } @Bean public ClientHttpRequestFactory getClientHttpRequestFactory() { // 保持长连接配置,需要在头添加Keep-Alive final ConnectionKeepAliveStrategy myStrategy = new ConnectionKeepAliveStrategy() { @Override public long getKeepAliveDuration(org.apache.http.HttpResponse response, HttpContext context) { // 设置一个链接的最大存活时间 return 5 * 1000L; } }; PoolingHttpClientConnectionManager pollingConnectionManager = new PoolingHttpClientConnectionManager( 30 , TimeUnit.SECONDS); pollingConnectionManager.setMaxTotal( 2000 ); //最大连接数 pollingConnectionManager.setDefaultMaxPerRoute( 200 ); //同路由的最大连接数 CloseableHttpClient closeableHttpClient = HttpClientBuilder.create().setConnectionManager(pollingConnectionManager).setKeepAliveStrategy(myStrategy).build(); HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory(closeableHttpClient); factory.setConnectTimeout( 3000 ); factory.setReadTimeout( 5000 ); return factory; } } |
2、使用jdk原生的
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
// 添加消息转换器 List messageConverters = new ArrayList(); messageConverters.add( new StringHttpMessageConverter()); messageConverters.add( new MappingJackson2HttpMessageConverter()); //如果useJ2SEHttp申明为true,则使用JDK自带的HttpURLConnection SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory(); requestFactory.setReadTimeout( 3000 ); requestFactory.setConnectTimeout( 3000 ); restTemplate = new RestTemplate(requestFactory); restTemplate.setMessageConverters(messageConverters); //这里是添加了拦截器 List<ClientHttpRequestInterceptor> interceptorList = new ArrayList<ClientHttpRequestInterceptor>(); interceptorList.add( new RequestInteceptor()); restTemplate.setInterceptors(interceptorList); |
2、拦截器实现ClientHttpRequestInterceptor
(设置头信息的时候回使用到)
1
2
3
4
5
6
7
8
9
|
public class RequestInteceptor implements ClientHttpRequestInterceptor { @Override public ClientHttpResponse intercept(HttpRequest request, byte [] body, ClientHttpRequestExecution execution) throws IOException { request.getHeaders().setAll(AppMetadataUtil.getAPP_METADATA()); String traceId = UUID.randomUUID().toString().replaceAll( "-" , "" ); request.getHeaders().set( "TraceId" , traceId.toString()); return execution.execute(request, body); } } |
4、常用的方法
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
String url = queryInfo?userId={userId}&pageIndex={pageIndex}&pageSize={pageSize}"; HashMap<String,Object> parameterMap = new HashMap<String,Object>(); parameterMap.put( "userId" , userId); parameterMap.put( "pageIndex" , pageIndex); parameterMap.put( "pageSize" , pageSize); String str = restTemplate.getForObject(url, String. class , parameterMap); String result = restTemp.getForObject(requestUrl.toString(), String. class ); //post String url = "http://www.xxx.com/queryInfo" String str = restTemplate.postForObject(url, parameterMap, String. class ); //exchange 设置请求头 HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.parseMediaType( "application/json;charset=UTF-8" )); headers.add( "Accept" , "application/json;charset=UTF-8" ); HttpEntity<String> httpEntity = new HttpEntity<String>( "" , headers); RestTemplate restTemplate = RestTemplateUtils.getInstance().getRestTemplate(); ResponseEntity<String> exchange = restTemplate.exchange(retailOrderUrl, HttpMethod.GET, httpEntity, String. class ); String forObject = exchange.getBody(); MultiValueMap<String, Object> requestEntity = new LinkedMultiValueMap<>(); |
以上为个人经验,希望能给大家一个参考,也希望大家多多支持服务器之家。
原文链接:https://blog.csdn.net/qq9808/article/details/105647182