东营网站建设策划内容,兰州快速seo整站优化招商,seo网站有哪些,WordPress整篇文章登录可见在Java开发中#xff0c;访问第三方HTTP协议的网络接口#xff0c;通常使用的连接工具为JDK自带的HttpURLConnection、HttpClient#xff08;现在应该称之为HttpComponents#xff09;和OKHttp。
这些Http连接工具#xff0c;使用起来都比较复杂#xff0c;如果项目中使…在Java开发中访问第三方HTTP协议的网络接口通常使用的连接工具为JDK自带的HttpURLConnection、HttpClient现在应该称之为HttpComponents和OKHttp。
这些Http连接工具使用起来都比较复杂如果项目中使用的是Spring框架可以使用Spring自带的RestTemplate来进行Http连接请求。
RestTemplate底层默认的连接方式是Java中的HttpURLConnection可以使用ClientHttpRequestFactory来指定底层使用不同的HTTP连接方式。
RestTemplate中默认的连接方式
RestTemplate中默认使用的是SimpleClientHttpRequestFactory我们这里手动创建SimpleClientHttpRequestFactory可以指定连接的超时时间读数据的超时时间。
package com.morris.user.demo;import com.morris.user.entity.Order;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;/*** restTemplatehttpUrlConnection*/
Slf4j
public class RestTemplateDemo1 {public static void main(String[] args) {SimpleClientHttpRequestFactory factory new SimpleClientHttpRequestFactory();factory.setConnectTimeout(3000);factory.setReadTimeout(5000);RestTemplate restTemplate new RestTemplate(factory);Order[] orders restTemplate.getForObject(http://127.0.0.1:8020/order/findOrderByUserId?userId, Order[].class, 1);log.info(orders :{}, orders);}}SimpleClientHttpRequestFactory底层在创建请求的时候使用的就是HttpURLConnection。
org.springframework.http.client.SimpleClientHttpRequestFactory#createRequest
public ClientHttpRequest createRequest(URI uri, HttpMethod httpMethod) throws IOException {HttpURLConnection connection openConnection(uri.toURL(), this.proxy);prepareConnection(connection, httpMethod.name());if (this.bufferRequestBody) {return new SimpleBufferingClientHttpRequest(connection, this.outputStreaming);}else {return new SimpleStreamingClientHttpRequest(connection, this.chunkSize, this.outputStreaming);}
}RestTemplate与HttpClient的结合
只需要在构造RestTemplate实例时传入HttpComponentsClientHttpRequestFactory对象即可。
package com.morris.user.demo;import com.morris.user.entity.Order;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;/*** RestTemplateHttpClient*/
Slf4j
public class RestTemplateDemo2 {public static void main(String[] args) {HttpComponentsClientHttpRequestFactory factory new HttpComponentsClientHttpRequestFactory();RestTemplate restTemplate new RestTemplate(factory);Order[] orders restTemplate.getForObject(http://127.0.0.1:8020/order/findOrderByUserId?userId, Order[].class, 1);log.info(orders :{}, orders);}}HttpComponentsClientHttpRequestFactory底层在创建请求时使用了HttpClient。 org.springframework.http.client.HttpComponentsClientHttpRequestFactory#createRequest
public ClientHttpRequest createRequest(URI uri, HttpMethod httpMethod) throws IOException {HttpClient client getHttpClient();HttpUriRequest httpRequest createHttpUriRequest(httpMethod, uri);postProcessHttpRequest(httpRequest);HttpContext context createHttpContext(httpMethod, uri);if (context null) {context HttpClientContext.create();}// Request configuration not set in the contextif (context.getAttribute(HttpClientContext.REQUEST_CONFIG) null) {// Use request configuration given by the user, when availableRequestConfig config null;if (httpRequest instanceof Configurable) {config ((Configurable) httpRequest).getConfig();}if (config null) {config createRequestConfig(client);}if (config ! null) {context.setAttribute(HttpClientContext.REQUEST_CONFIG, config);}}if (this.bufferRequestBody) {return new HttpComponentsClientHttpRequest(client, httpRequest, context);}else {return new HttpComponentsStreamingClientHttpRequest(client, httpRequest, context);}
}RestTemplate与HttpClient的在生产环境使用的最佳实践
在构建HttpClient时经常需要配置很多信息例如RequestTimeout、ConnectTimeout、SocketTimeout、代理、是否允许重定向、连接池等信息。
在HttpClient对这些参数进行配置需要使用到RequestConfig类的一个内部类Builder。
这里将这些常用的配置抽取出来放到配置文件中
package com.morris.user.config;import lombok.extern.slf4j.Slf4j;
import org.apache.http.HeaderElement;
import org.apache.http.HeaderElementIterator;
import org.apache.http.HttpHost;
import org.apache.http.client.HttpClient;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.ConnectionKeepAliveStrategy;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpRequestRetryHandler;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicHeaderElementIterator;
import org.apache.http.protocol.HTTP;
import org.apache.http.ssl.SSLContextBuilder;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;import javax.annotation.Resource;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLContext;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;EnableConfigurationProperties(HttpClientConfig.class)
ConditionalOnClass(RestTemplate.class)
Configuration
Slf4j
public class RestTemplateAutoConfiguration {Resourceprivate HttpClientConfig httpClientConfig;BeanConditionalOnClass(CloseableHttpClient.class)public RestTemplate httpClientRestTemplate(ClientHttpRequestFactory clientHttpRequestFactory){return new RestTemplate(clientHttpRequestFactory);}BeanConditionalOnClass(CloseableHttpClient.class)public ClientHttpRequestFactory clientHttpRequestFactory(HttpClient httpClient) {HttpComponentsClientHttpRequestFactory clientHttpRequestFactory new HttpComponentsClientHttpRequestFactory();clientHttpRequestFactory.setHttpClient(httpClient);clientHttpRequestFactory.setConnectTimeout(httpClientConfig.getRequest().getConnectTimeout());clientHttpRequestFactory.setReadTimeout(httpClientConfig.getRequest().getReadTimeout());clientHttpRequestFactory.setConnectionRequestTimeout(httpClientConfig.getRequest().getConnectionRequestTimeout());clientHttpRequestFactory.setBufferRequestBody(httpClientConfig.getRequest().isBufferRequestBody());return clientHttpRequestFactory;}BeanPrimaryConditionalOnClass(CloseableHttpClient.class)public HttpClient httpClient() throws NoSuchAlgorithmException, KeyStoreException, KeyManagementException {HttpClientBuilder httpClientBuilder HttpClientBuilder.create();try {// 设置信任SSL访问SSLContext sslContext new SSLContextBuilder().loadTrustMaterial(null, (arg0, arg1) - true).build();httpClientBuilder.setSSLContext(sslContext);// 任何主机都不会抛出SSLException异常HostnameVerifier hostnameVerifier NoopHostnameVerifier.INSTANCE;SSLConnectionSocketFactory sslConnectionSocketFactory new SSLConnectionSocketFactory(sslContext, hostnameVerifier);RegistryConnectionSocketFactory socketFactoryRegistry RegistryBuilder.ConnectionSocketFactorycreate()// 注册HTTP和HTTPS请求.register(http, PlainConnectionSocketFactory.getSocketFactory()).register(https, sslConnectionSocketFactory).build();// 使用Httpclient连接池的方式配置PoolingHttpClientConnectionManager poolingHttpClientConnectionManager new PoolingHttpClientConnectionManager(socketFactoryRegistry);poolingHttpClientConnectionManager.setMaxTotal(httpClientConfig.getPool().getMaxTotalConnect());poolingHttpClientConnectionManager.setDefaultMaxPerRoute(httpClientConfig.getPool().getMaxConnectPerRoute());poolingHttpClientConnectionManager.setValidateAfterInactivity(httpClientConfig.getPool().getValidateAfterInactivity());httpClientBuilder.setConnectionManager(poolingHttpClientConnectionManager);httpClientBuilder.setRetryHandler(new DefaultHttpRequestRetryHandler(httpClientConfig.getPool().getRetryTimes(), true));httpClientBuilder.setKeepAliveStrategy(connectionKeepAliveStrategy());return httpClientBuilder.build();} catch (KeyManagementException | NoSuchAlgorithmException | KeyStoreException e) {log.error(初始化HTTP连接池出错, e);throw e;}}/*** 配置长连接保持策略* return ConnectionKeepAliveStrategy*/public ConnectionKeepAliveStrategy connectionKeepAliveStrategy(){return (response, context) - {// Honor keep-alive headerHeaderElementIterator it new BasicHeaderElementIterator(response.headerIterator(HTTP.CONN_KEEP_ALIVE));while (it.hasNext()) {HeaderElement he it.nextElement();String param he.getName();String value he.getValue();if (value ! null timeout.equalsIgnoreCase(param)) {try {return Long.parseLong(value) * 1000;} catch(NumberFormatException error) {log.error(解析长连接过期时间异常, error);}}}HttpHost target (HttpHost) context.getAttribute(HttpClientContext.HTTP_TARGET_HOST);//如果请求目标地址,单独配置了长连接保持时间,使用该配置OptionalMap.EntryString, Integer any Optional.ofNullable(httpClientConfig.getPool().getKeepAliveTargetHost()).orElseGet(HashMap::new).entrySet().stream().filter(e - e.getKey().equalsIgnoreCase(target.getHostName())).findAny();//否则使用默认长连接保持时间return any.map(en - en.getValue() * 1000L).orElse(httpClientConfig.getPool().getKeepAliveTime() * 1000L);};}}
文章转载自: http://www.morning.xyrw.cn.gov.cn.xyrw.cn http://www.morning.mnwb.cn.gov.cn.mnwb.cn http://www.morning.ljbm.cn.gov.cn.ljbm.cn http://www.morning.ypjjh.cn.gov.cn.ypjjh.cn http://www.morning.bnxnq.cn.gov.cn.bnxnq.cn http://www.morning.hhfqk.cn.gov.cn.hhfqk.cn http://www.morning.yfwygl.cn.gov.cn.yfwygl.cn http://www.morning.rgfx.cn.gov.cn.rgfx.cn http://www.morning.clndl.cn.gov.cn.clndl.cn http://www.morning.pjyrl.cn.gov.cn.pjyrl.cn http://www.morning.lkfsk.cn.gov.cn.lkfsk.cn http://www.morning.pskjm.cn.gov.cn.pskjm.cn http://www.morning.jhqcr.cn.gov.cn.jhqcr.cn http://www.morning.rbgqn.cn.gov.cn.rbgqn.cn http://www.morning.xqkjp.cn.gov.cn.xqkjp.cn http://www.morning.fygbq.cn.gov.cn.fygbq.cn http://www.morning.bqnhh.cn.gov.cn.bqnhh.cn http://www.morning.htjwz.cn.gov.cn.htjwz.cn http://www.morning.gbqgr.cn.gov.cn.gbqgr.cn http://www.morning.rkmhp.cn.gov.cn.rkmhp.cn http://www.morning.rkkpr.cn.gov.cn.rkkpr.cn http://www.morning.qkcyk.cn.gov.cn.qkcyk.cn http://www.morning.rnzgf.cn.gov.cn.rnzgf.cn http://www.morning.gdgylp.com.gov.cn.gdgylp.com http://www.morning.deupp.com.gov.cn.deupp.com http://www.morning.kqpq.cn.gov.cn.kqpq.cn http://www.morning.pamdeer.com.gov.cn.pamdeer.com http://www.morning.gjwkl.cn.gov.cn.gjwkl.cn http://www.morning.fktlg.cn.gov.cn.fktlg.cn http://www.morning.pzbjy.cn.gov.cn.pzbjy.cn http://www.morning.tgwfn.cn.gov.cn.tgwfn.cn http://www.morning.tlrxt.cn.gov.cn.tlrxt.cn http://www.morning.zpyxl.cn.gov.cn.zpyxl.cn http://www.morning.gwsll.cn.gov.cn.gwsll.cn http://www.morning.rmdwp.cn.gov.cn.rmdwp.cn http://www.morning.mpxbl.cn.gov.cn.mpxbl.cn http://www.morning.burpgr.cn.gov.cn.burpgr.cn http://www.morning.rzmzm.cn.gov.cn.rzmzm.cn http://www.morning.pflpb.cn.gov.cn.pflpb.cn http://www.morning.nflpk.cn.gov.cn.nflpk.cn http://www.morning.ysbrz.cn.gov.cn.ysbrz.cn http://www.morning.nrll.cn.gov.cn.nrll.cn http://www.morning.ngzkt.cn.gov.cn.ngzkt.cn http://www.morning.cfocyfa.cn.gov.cn.cfocyfa.cn http://www.morning.wkrkb.cn.gov.cn.wkrkb.cn http://www.morning.rbzht.cn.gov.cn.rbzht.cn http://www.morning.tdldh.cn.gov.cn.tdldh.cn http://www.morning.mrbzq.cn.gov.cn.mrbzq.cn http://www.morning.fldsb.cn.gov.cn.fldsb.cn http://www.morning.fygbq.cn.gov.cn.fygbq.cn http://www.morning.qdlr.cn.gov.cn.qdlr.cn http://www.morning.ybgcn.cn.gov.cn.ybgcn.cn http://www.morning.tpxgm.cn.gov.cn.tpxgm.cn http://www.morning.hmbtb.cn.gov.cn.hmbtb.cn http://www.morning.ybgpk.cn.gov.cn.ybgpk.cn http://www.morning.wchcx.cn.gov.cn.wchcx.cn http://www.morning.qsszq.cn.gov.cn.qsszq.cn http://www.morning.bxnrx.cn.gov.cn.bxnrx.cn http://www.morning.hxhrg.cn.gov.cn.hxhrg.cn http://www.morning.rgdcf.cn.gov.cn.rgdcf.cn http://www.morning.kpzbf.cn.gov.cn.kpzbf.cn http://www.morning.mxdiy.com.gov.cn.mxdiy.com http://www.morning.rwnx.cn.gov.cn.rwnx.cn http://www.morning.gwqkk.cn.gov.cn.gwqkk.cn http://www.morning.sgcdr.com.gov.cn.sgcdr.com http://www.morning.yrccw.cn.gov.cn.yrccw.cn http://www.morning.eviap.com.gov.cn.eviap.com http://www.morning.cgtfl.cn.gov.cn.cgtfl.cn http://www.morning.ychrn.cn.gov.cn.ychrn.cn http://www.morning.mnjyf.cn.gov.cn.mnjyf.cn http://www.morning.tjwfk.cn.gov.cn.tjwfk.cn http://www.morning.ldqzz.cn.gov.cn.ldqzz.cn http://www.morning.gtbjf.cn.gov.cn.gtbjf.cn http://www.morning.yfmwg.cn.gov.cn.yfmwg.cn http://www.morning.hwlk.cn.gov.cn.hwlk.cn http://www.morning.cyjjp.cn.gov.cn.cyjjp.cn http://www.morning.rczrq.cn.gov.cn.rczrq.cn http://www.morning.wfyqn.cn.gov.cn.wfyqn.cn http://www.morning.bhbxd.cn.gov.cn.bhbxd.cn http://www.morning.rmkyb.cn.gov.cn.rmkyb.cn