ClientConfiguration.java

该类讲解了HttpClient的各方面的配置

package com.ydd.study.hello.httpclient;import java.net.InetAddress;
import java.net.UnknownHostException;
import java.nio.charset.CodingErrorAction;
import java.util.Arrays;import javax.net.ssl.SSLContext;import org.apache.http.Consts;
import org.apache.http.Header;
import org.apache.http.HttpHost;
import org.apache.http.HttpRequest;
import org.apache.http.HttpResponse;
import org.apache.http.ParseException;
import org.apache.http.client.CookieStore;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.config.AuthSchemes;
import org.apache.http.client.config.CookieSpecs;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.config.ConnectionConfig;
import org.apache.http.config.MessageConstraints;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.config.SocketConfig;
import org.apache.http.conn.DnsResolver;
import org.apache.http.conn.HttpConnectionFactory;
import org.apache.http.conn.ManagedHttpClientConnection;
import org.apache.http.conn.routing.HttpRoute;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.impl.DefaultHttpResponseFactory;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.DefaultHttpResponseParser;
import org.apache.http.impl.conn.DefaultHttpResponseParserFactory;
import org.apache.http.impl.conn.ManagedHttpClientConnectionFactory;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.impl.conn.SystemDefaultDnsResolver;
import org.apache.http.impl.io.DefaultHttpRequestWriterFactory;
import org.apache.http.io.HttpMessageParser;
import org.apache.http.io.HttpMessageParserFactory;
import org.apache.http.io.HttpMessageWriterFactory;
import org.apache.http.io.SessionInputBuffer;
import org.apache.http.message.BasicHeader;
import org.apache.http.message.BasicLineParser;
import org.apache.http.message.LineParser;
import org.apache.http.ssl.SSLContexts;
import org.apache.http.util.CharArrayBuffer;
import org.apache.http.util.EntityUtils;public class ClientConfiguration {public final static void main(String[] args) throws Exception {// Use custom message parser / writer to customize the way HTTP// messages are parsed from and written out to the data stream.HttpMessageParserFactory<HttpResponse> responseParserFactory = new DefaultHttpResponseParserFactory() {@Overridepublic HttpMessageParser<HttpResponse> create(SessionInputBuffer buffer, MessageConstraints constraints) {LineParser lineParser = new BasicLineParser() {@Overridepublic Header parseHeader(final CharArrayBuffer buffer) {try {return super.parseHeader(buffer);} catch (ParseException ex) {return new BasicHeader(buffer.toString(), null);}}};return new DefaultHttpResponseParser(buffer, lineParser, DefaultHttpResponseFactory.INSTANCE, constraints) {@Overrideprotected boolean reject(final CharArrayBuffer line, int count) {// try to ignore all garbage preceding a status line infinitelyreturn false;}};}};HttpMessageWriterFactory<HttpRequest> requestWriterFactory = new DefaultHttpRequestWriterFactory();// Use a custom connection factory to customize the process of// initialization of outgoing HTTP connections. Beside standard connection// configuration parameters HTTP connection factory can define message// parser / writer routines to be employed by individual connections.HttpConnectionFactory<HttpRoute, ManagedHttpClientConnection> connFactory = new ManagedHttpClientConnectionFactory(requestWriterFactory, responseParserFactory);// Client HTTP connection objects when fully initialized can be bound to// an arbitrary network socket. The process of network socket initialization,// its connection to a remote address and binding to a local one is controlled// by a connection socket factory.// SSL context for secure connections can be created either based on// system or application specific properties.SSLContext sslcontext = SSLContexts.createSystemDefault();// Create a registry of custom connection socket factories for supported// protocol schemes.Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create().register("http", PlainConnectionSocketFactory.INSTANCE).register("https", new SSLConnectionSocketFactory(sslcontext)).build();// Use custom DNS resolver to override the system DNS resolution.DnsResolver dnsResolver = new SystemDefaultDnsResolver() {@Overridepublic InetAddress[] resolve(final String host) throws UnknownHostException {if (host.equalsIgnoreCase("myhost")) {return new InetAddress[] { InetAddress.getByAddress(new byte[] {127, 0, 0, 1}) };} else {return super.resolve(host);}}};// Create a connection manager with custom configuration.PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry, connFactory, dnsResolver);// Create socket configurationSocketConfig socketConfig = SocketConfig.custom().setTcpNoDelay(true).build();// Configure the connection manager to use socket configuration either// by default or for a specific host.
            connManager.setDefaultSocketConfig(socketConfig);connManager.setSocketConfig(new HttpHost("somehost", 80), socketConfig);// Validate connections after 1 sec of inactivityconnManager.setValidateAfterInactivity(1000);// Create message constraintsMessageConstraints messageConstraints = MessageConstraints.custom().setMaxHeaderCount(200).setMaxLineLength(2000).build();// Create connection configurationConnectionConfig connectionConfig = ConnectionConfig.custom().setMalformedInputAction(CodingErrorAction.IGNORE).setUnmappableInputAction(CodingErrorAction.IGNORE).setCharset(Consts.UTF_8).setMessageConstraints(messageConstraints).build();// Configure the connection manager to use connection configuration either// by default or for a specific host.
            connManager.setDefaultConnectionConfig(connectionConfig);connManager.setConnectionConfig(new HttpHost("somehost", 80), ConnectionConfig.DEFAULT);// Configure total max or per route limits for persistent connections// that can be kept in the pool or leased by the connection manager.connManager.setMaxTotal(100);connManager.setDefaultMaxPerRoute(10);connManager.setMaxPerRoute(new HttpRoute(new HttpHost("somehost", 80)), 20);// Use custom cookie store if necessary.CookieStore cookieStore = new BasicCookieStore();// Use custom credentials provider if necessary.CredentialsProvider credentialsProvider = new BasicCredentialsProvider();// Create global request configurationRequestConfig defaultRequestConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.DEFAULT).setExpectContinueEnabled(true).setTargetPreferredAuthSchemes(Arrays.asList(AuthSchemes.NTLM, AuthSchemes.DIGEST)).setProxyPreferredAuthSchemes(Arrays.asList(AuthSchemes.BASIC)).build();// Create an HttpClient with the given custom dependencies and configuration.CloseableHttpClient httpclient = HttpClients.custom().setConnectionManager(connManager).setDefaultCookieStore(cookieStore).setDefaultCredentialsProvider(credentialsProvider).setProxy(new HttpHost("myproxy", 8080)).setDefaultRequestConfig(defaultRequestConfig).build();try {HttpGet httpget = new HttpGet("http://httpbin.org/get");// Request configuration can be overridden at the request level.// They will take precedence over the one set at the client level.RequestConfig requestConfig = RequestConfig.copy(defaultRequestConfig).setSocketTimeout(5000).setConnectTimeout(5000).setConnectionRequestTimeout(5000).setProxy(new HttpHost("myotherproxy", 8080)).build();httpget.setConfig(requestConfig);// Execution context can be customized locally.HttpClientContext context = HttpClientContext.create();// Contextual attributes set the local context level will take// precedence over those set at the client level.
                context.setCookieStore(cookieStore);context.setCredentialsProvider(credentialsProvider);System.out.println("executing request " + httpget.getURI());CloseableHttpResponse response = httpclient.execute(httpget, context);try {System.out.println("----------------------------------------");System.out.println(response.getStatusLine());System.out.println(EntityUtils.toString(response.getEntity()));System.out.println("----------------------------------------");// Once the request has been executed the local context can// be used to examine updated state and various objects affected// by the request execution.// Last executed request
                    context.getRequest();// Execution route
                    context.getHttpRoute();// Target auth state
                    context.getTargetAuthState();// Proxy auth state
                    context.getTargetAuthState();// Cookie origin
                    context.getCookieOrigin();// Cookie spec used
                    context.getCookieSpec();// User security token
                    context.getUserToken();} finally {response.close();}} finally {httpclient.close();}}
}

https://hc.apache.org/httpcomponents-client-ga/httpclient/examples/org/apache/http/examples/client/ClientConnectionRelease.java

转载于:https://www.cnblogs.com/YDDMAX/p/5379632.html

HttpClient配置相关推荐

  1. angular HttpClient 配置

    angular的资料很少,并且坑很多,报错也不是很好解决,研究这个花了好几天时间. 首先,先查看自己的anuglar版本是不是4.3.0以上,HttpClient是anuglar4.3中新加入的特性, ...

  2. 修复.NET的HttpClient

    \ 看新闻很累?看技术新闻更累?试试下载InfoQ手机客户端,每天上下班路上听新闻,有趣还有料! \ \\ 早在2016年我们就报道过 ,.NET的HttpClient存在一些问题.随着.NET Co ...

  3. HttpClient:绕开https证书(三)

    HTTP 协议可能是现在 Internet 上使用得最多.最重要的协议了,越来越多的 Java 应用程序需要直接通过 HTTP 协议来访问网络资源.虽然在 JDK 的 java.net 包中已经提供了 ...

  4. httpclient封装获取响应实体_Httpclient 接口自动化

    好久木写啦!!!好久木写啦!!! 心血来潮分享点小白的东西!!! 废话少说直接干货!!! 本文核心是将如何从数据驱动开始,以报告结尾的形式来实现"很多刚入行朋友们"所需要的接口自动 ...

  5. Android开发实现HttpClient工具类

    在Android开发中我们经常会用到网络连接功能与服务器进行数据的交互,为此Android的SDK提供了Apache的HttpClient来方便我们使用各种Http服务.你可以把HttpClient想 ...

  6. 使用单例模式实现自己的HttpClient工具类

    本文转载自:http://www.cnblogs.com/codingmyworld/archive/2011/08/17/2141706.html 使用单例模式实现自己的HttpClient工具类 ...

  7. Java代码 httpClient请求 响应 爬虫

    public class httpClientStuParam06Test {@Testpublic void getParam() throws URISyntaxException {System ...

  8. HttpClient发送Https请求报 : unable to find valid certification path to requested target

    一.场景   近期在对接第三方接口时,通过HttpClient发送Https请求报 : unable to find valid certification path to requested tar ...

  9. android httpclient单例模式

    在Android开发中我们经常会用到网络连接功能与服务器进行数据的交互,为此Android的SDK提供了Apache的HttpClient来方便我们使用各种Http服务.你可以把HttpClient想 ...

  10. JAVA——Okhttp封装工具类

    基本概念 OKhttp:一个处理网络请求的开源项目,是安卓端最火热的轻量级框架. Maven <!--OK HTTP Client--><dependency><grou ...

最新文章

  1. 基于SSH框架实际开发时遇到的问题及解决办法
  2. 2017年热度最高的十大技术类技能
  3. 20个linux常用命令,Linux20个常用命令整理(基础)
  4. 人员梯度培养_人员管理 | 生产班组员工队伍管理及制度建立
  5. VIM常用的编辑操作
  6. 论文参考文献格式标准~收藏
  7. 深度学习C++代码配套教程(1. 总述)
  8. php运行方式isapi,PHP_WINDOWS 2000下使用ISAPI方式安装PHP,使用ISAPI方式安装PHP。 下载连 - phpStudy...
  9. 尺缩钟慢之动钟变慢——思想实验推导狭义相对论(七)
  10. 4G内存适合装哪个版本matlab,4G内存装win7 32位还是64位|单条4G内存选32位还是64位系统性能实测...
  11. SpringBoot启动成功后,访问接口报错404(error:“Not Found“)
  12. MySQL 自增长主键 在删除数据后依然接着删除的数据增长
  13. DStream转换操作
  14. 诺威达K2201s/全志p9处理器/线刷救砖包
  15. 解决非标属性和低流动性,未来加密投资的黑马赛道
  16. 【mysql】 踩坑记录之derived(派生表)
  17. Java中POJO及其细分XO、DAO的概念
  18. SpringMVC工作流程
  19. RationalDMIS 7.1 更新实际元素:
  20. matlab生成代码veri,一种自动生成状态机RTL代码的方法

热门文章

  1. 商业流程中的traversedpath
  2. 网摘Android调用WebService
  3. Ext中Date format含义
  4. oracle桌面工具plsql连接本地远程数据库
  5. oracle中varchar2和nvarchar2的区别
  6. Jquery、简单的下拉列表、网页左部导航菜单
  7. Vue使用Axios实现http请求以及解决跨域问题
  8. PowerDesigner逆向工程,从SQL Server数据库生成Physical Model
  9. 移动端的头部标签和meta
  10. 循环数组实现队列的四种方式