RestTemplate使用封装

正文
之前接口调用习惯性使用HttpClient,代码复杂,冗余代码多,关心资源回收用起来不是很爽。
RestTemplate默认依赖jdk的HTTP连接工具。也可以 通过setRequestFactory属性切换到不同的HTTP源,比如Apache HttpComponents、Netty、OkHttp。
一、SpringBoot使用RestTemplate(使用apache的httpclient)


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;
    }
}

二、使用jdk原生的

            // 添加消息转换器
			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);

三、拦截器实现ClientHttpRequestInterceptor(设置头信息的时候回使用到)

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);
    }
}

四、常用的方法

	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<>();

你可能感兴趣的:(JAVA)