HttpClient之参数设置

    HttpClient中的参数设置主要包括:请求头Header,响应头Header、主机配置信息、及管理连接的参数设置。

    包org.apache.commons.httpclient.params中的各个类用于HttpClient整个调用过程中参数的设置,开发者直接调用使用的包括HttpConnectionManagerParams、HttpClientParams、HostParams。

    HttpConnectionManagerParams:服务器与客户端的连接参数,用于httpclient. httpConnectionManager的配置

    HttpClientParams:管理各个协议各种请求信息,包括:请求头、响应头等,用于httpclient. httpClientParams的配置

    HostParams:主机配置信息,用于httpclient. hostConfiguration的配置。

一、Header 

Requests部分

Header

解释

示例

Accept

指定客户端能够接收的内容类型

Accept: text/plain, text/html

Accept-Charset

浏览器可以接受的字符编码集。

Accept-Charset: iso-8859-5

Accept-Encoding

指定浏览器可以支持的web服务器返回内容压缩编码类型。

Accept-Encoding: compress, gzip

Accept-Language

浏览器可接受的语言

Accept-Language: en,zh

Accept-Ranges

可以请求网页实体的一个或者多个子范围字段

Accept-Ranges: bytes

Authorization

HTTP授权的授权证书

Authorization: Basic  QWxhZGRpbjpvcGVuIHNlc2FtZQ==

Cache-Control

指定请求和响应遵循的缓存机制

Cache-Control: no-cache

Connection

表示是否需要持久连接。(HTTP  1.1默认进行持久连接)

Connection: close

Cookie

HTTP请求发送时,会把保存在该请求域名下的所有cookie值一起发送给web服务器。

Cookie: $Version=1; Skin=new;

Content-Length

请求的内容长度

Content-Length: 348

Content-Type

请求的与实体对应的MIME信息

Content-Type:  application/x-www-form-urlencoded

Date

请求发送的日期和时间

Date: Tue, 15 Nov 2010 08:12:31 GMT

Expect

请求的特定的服务器行为

Expect: 100-continue

From

发出请求的用户的Email

From: user@email.com

Host

指定请求的服务器的域名和端口号

Host: www.zcmhi.com

If-Match

只有请求内容与实体相匹配才有效

If-Match:  “737060cd8c284d8af7ad3082f209582d”

If-Modified-Since

如果请求的部分在指定时间之后被修改则请求成功,未被修改则返回304代码

If-Modified-Since: Sat, 29 Oct 2010  19:43:31 GMT

If-None-Match

如果内容未改变返回304代码,参数为服务器先前发送的Etag,与服务器回应的Etag比较判断是否改变

If-None-Match:  “737060cd8c284d8af7ad3082f209582d”

If-Range

如果实体未改变,服务器发送客户端丢失的部分,否则发送整个实体。参数也为Etag

If-Range:  “737060cd8c284d8af7ad3082f209582d”

If-Unmodified-Since

只在实体在指定时间之后未被修改才请求成功

If-Unmodified-Since: Sat, 29 Oct 2010 19:43:31 GMT

Max-Forwards

限制信息通过代理和网关传送的时间

Max-Forwards: 10

Pragma

用来包含实现特定的指令

Pragma: no-cache

Proxy-Authorization

连接到代理的授权证书

Proxy-Authorization: Basic  QWxhZGRpbjpvcGVuIHNlc2FtZQ==

Range

只请求实体的一部分,指定范围

Range: bytes=500-999

Referer

先前网页的地址,当前请求网页紧随其后,即来路

Referer:  http://www.zcmhi.com/archives/71.html

TE

客户端愿意接受的传输编码,并通知服务器接受接受尾加头信息

TE: trailers,deflate;q=0.5

Upgrade

向服务器指定某种传输协议以便服务器进行转换(如果支持)

Upgrade: HTTP/2.0, SHTTP/1.3, IRC/6.9,  RTA/x11

User-Agent

User-Agent的内容包含发出请求的用户信息

User-Agent: Mozilla/5.0 (Linux; X11)

Via

通知中间网关或代理服务器地址,通信协议

Via: 1.0 fred, 1.1 nowhere.com (Apache/1.1)

Warning

关于消息实体的警告信息

Warn: 199 Miscellaneous warning

 

Responses部分

Header

解释

示例

Accept-Ranges

表明服务器是否支持指定范围请求及哪种类型的分段请求

Accept-Ranges: bytes

Age

从原始服务器到代理缓存形成的估算时间(以秒计,非负)

Age: 12

Allow

对某网络资源的有效的请求行为,不允许则返回405

Allow: GET, HEAD

Cache-Control

告诉所有的缓存机制是否可以缓存及哪种类型

Cache-Control: no-cache

Content-Encoding

web服务器支持的返回内容压缩编码类型。

Content-Encoding: gzip

Content-Language

响应体的语言

Content-Language: en,zh

Content-Length

响应体的长度

Content-Length: 348

Content-Location

请求资源可替代的备用的另一地址

Content-Location: /index.htm

Content-MD5

返回资源的MD5校验值

Content-MD5: Q2hlY2sgSW50ZWdyaXR5IQ==

Content-Range

在整个返回体中本部分的字节位置

Content-Range: bytes 21010-47021/47022

Content-Type

返回内容的MIME类型

Content-Type: text/html; charset=utf-8

Date

原始服务器消息发出的时间

Date: Tue, 15 Nov 2010 08:12:31 GMT

ETag

请求变量的实体标签的当前值

ETag: “737060cd8c284d8af7ad3082f209582d”

Expires

响应过期的日期和时间

Expires: Thu, 01 Dec 2010 16:00:00 GMT

Last-Modified

请求资源的最后修改时间

Last-Modified: Tue, 15 Nov 2010 12:45:26  GMT

Location

用来重定向接收方到非请求URL的位置来完成请求或标识新的资源

Location:  http://www.zcmhi.com/archives/94.html

Pragma

包括实现特定的指令,它可应用到响应链上的任何接收方

Pragma: no-cache

Proxy-Authenticate

它指出认证方案和可应用到代理的该URL上的参数

Proxy-Authenticate: Basic

refresh

应用于重定向或一个新的资源被创造,在5秒之后重定向(由网景提出,被大部分浏览器支持)

 Refresh: 5; url=http://www.zcmhi.com/archives/94.html

Retry-After

如果实体暂时不可取,通知客户端在指定时间之后再次尝试

Retry-After: 120

Server

web服务器软件名称

Server: Apache/1.3.27 (Unix)  (Red-Hat/Linux)

Set-Cookie

设置Http  Cookie

Set-Cookie: UserID=JohnDoe; Max-Age=3600;  Version=1

Trailer

指出头域在分块传输编码的尾部存在

Trailer: Max-Forwards

Transfer-Encoding

文件传输编码

Transfer-Encoding:chunked

Vary

告诉下游代理是使用缓存响应还是从原始服务器请求

Vary: *

Via

告知代理客户端响应是通过哪里发送的

Via: 1.0 fred, 1.1 nowhere.com (Apache/1.1)

Warning

警告实体可能存在的问题

Warning: 199 Miscellaneous warning

WWW-Authenticate

表明客户端请求实体应该使用的授权方案

WWW-Authenticate: Basic

 

转载: http://kb.cnblogs.com/page/92320/

原始来源:w3c官网Header FieldDefinitions 网址:http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html

、包org.apache.commons.httpclient.params中类属性设定

HttpMethodParams

Applicable at thefollowing levels: global -> client -> host -> method

Name

Type

Description

Default

http.useragent

String

The content of the User-Agent header used by the HTTP methods.

official release name, e.g. "Jakarta  Commons-HttpClient/3.0"

http.protocol.version

HttpVersion

The HTTP protocol version used per default by the HTTP  methods.

HttpVersion.HTTP_1_1

http.protocol.unambiguous-statusline

Boolean

Defines whether HTTP methods should reject ambiguous  HTTP status line.

<undefined>

http.protocol.single-cookie-header

Boolean

Defines whether cookies should be put on a single  response header.

<undefined>

http.protocol.strict-transfer-encoding

Boolean

Defines whether responses with an invalid Transfer-Encoding header should be rejected.

<undefined>

http.protocol.reject-head-body

Boolean

Defines whether the content body sent in response  to HEAD request  should be rejected.

<undefined>

http.protocol.head-body-timeout

Integer

Sets period of time in milliseconds to wait for a  content body sent in response toHEAD response  from a non-compliant server. If the parameter is not set or set to-1 non-compliant response body  check is disabled.

<undefined>

http.protocol.expect-continue

Boolean

Activates 'Expect: 100-Continue' handshake for the  entity enclosing methods. The 'Expect: 100-Continue' handshake allows a  client that is sending a request message with a request body to determine if  the origin server is willing to accept the request (based on the request  headers) before the client sends the request body.

The use of the 'Expect: 100-continue' handshake can  result in noticeable performance improvement for entity enclosing requests  (such as POST and PUT) that require the target server's  authentication.

'Expect: 100-continue' handshake should be used with  caution, as it may cause problems with HTTP servers and proxies that do not  support HTTP/1.1 protocol.

<undefined>

http.protocol.credential-charset

String

The charset to be used when encoding credentials. If  not defined then the value of the 'http.protocol.element-charset' should be  used.

<undefined>

http.protocol.element-charset

String

The charset to be used for encoding/decoding HTTP  protocol elements (status line and headers).

'US-ASCII'

http.protocol.content-charset

String

The charset to be used for encoding content body.

'ISO-8859-1'

http.protocol.cookie-policy

String

The cookie policy to be used for cookie management.

CookiePolicy.RFC_2109

http.protocol.warn-extra-input

Boolean

Defines HttpClient's behavior when a response provides  more bytes than expected (specified with Content-Length header, for example).

Such surplus data makes the HTTP connection unreliable  for keep-alive requests, as malicious response data (faked headers etc.) can  lead to undesired results on the next request using that connection.

If this parameter is set to true, any detection of extra input data  will generate a warning in the log.

<undefined>

http.protocol.status-line-garbage-limit

Integer

Defines the maximum number of ignorable lines before we  expect a HTTP response's status code.

With HTTP/1.1 persistent connections, the problem  arises that broken scripts could return a wrong Content-Length (there are more bytes sent than specified).  Unfortunately, in some cases, this is not possible after the bad response,  but only before the next one. So, HttpClient must be able to skip those  surplus lines this way.

Set this to 0 to disallow any garbage/empty lines before the  status line. To specify no limit, use Integer#MAX_VALUE.

<undefined>

http.socket.timeout

Integer

Sets the socket timeout (SO_TIMEOUT) in milliseconds to be used when executing the method.  A timeout value of zero is interpreted as an infinite timeout.

<undefined>

http.method.retry-handler

HttpMethodRetryHandler

The method retry handler used for retrying failed  methods. For details see theException handling guide.

default implementation

http.dateparser.patterns

Collection

Date patterns used for parsing. The patterns are stored  in a Collection and  must be compatible with SimpleDateFormat.

'EEE, dd MMM yyyy HH:mm:ss zzz',
 
  'EEEE, dd-MMM-yy HH:mm:ss zzz',
 
  'EEE MMM d HH:mm:ss yyyy',
 
  'EEE, dd-MMM-yyyy HH:mm:ss z',
 
  'EEE, dd-MMM-yyyy HH-mm-ss z',
 
  'EEE, dd MMM yy HH:mm:ss z',
 
  'EEE dd-MMM-yyyy HH:mm:ss z',
 
  'EEE dd MMM yyyy HH:mm:ss z',
 
  'EEE dd-MMM-yyyy HH-mm-ss z',
 
  'EEE dd-MMM-yy HH:mm:ss z',
 
  'EEE dd MMM yy HH:mm:ss z',
 
  'EEE,dd-MMM-yy HH:mm:ss z',
 
  'EEE,dd-MMM-yyyy HH:mm:ss z',
 
  'EEE, dd-MM-yyyy HH:mm:ss z'

http.method.response.buffer.warnlimit

Integer

The maximum buffered response size (in bytes) that  triggers no warning. Buffered responses exceeding this size will trigger a  warning in the log. If not set, the limit is 1 MB.

<undefined>

http.method.multipart.boundary

String

The multipart boundary string to use in conjunction  with theMultipartRequestEntity. When not set a random  value will be generated for each request.

<undefined>

 

HttpClientParams

Applicable at thefollowing levels: global -> client

Name

Type

Description

Default

http.connection-manager.timeout

Long

The timeout in milliseconds used when retrieving an  HTTP connection from the HTTP connection manager. 0 means to wait  indefinitely.

<undefined>

http.connection-manager.class

Class

The default HTTP connection manager class.

SimpleHttpConnectionManagerclass

http.authentication.preemptive

Boolean

Defines whether authentication should be attempted  preemptively. See authentication guide.

<undefined>

http.protocol.reject-relative-redirect

Boolean

Defines whether relative redirects should be rejected.  Although redirects are supposed to be absolute it is common internet practice  to use relative URLs.

<undefined>

http.protocol.max-redirects

Integer

Defines the maximum number of redirects to be followed.  The limit on number of redirects is intended to prevent infinite loops.

<undefined>

http.protocol.allow-circular-redirects

Boolean

Defines whether circular redirects (redirects to the  same location) should be allowed. The HTTP spec is not sufficiently clear  whether circular redirects are permitted, therefore optionally they can be  enabled.

<undefined>

 

HttpConnectionParams

Applicable at thefollowing levels: global -> client -> connectionmanager -> connection

Name

Type

Description

Default

http.socket.timeout

Integer

The default socket timeout (SO_TIMEOUT) in milliseconds which is the timeout for waiting for  data. A timeout value of zero is interpreted as an infinite timeout. This  value is used when no socket timeout is set in the HTTP method parameters.

<undefined>

http.tcp.nodelay

Boolean

Determines whether Nagle's algorithm is to be used. The  Nagle's algorithm tries to conserve bandwidth by minimizing the number of  segments that are sent. When applications wish to decrease network latency  and increase performance, they can disable Nagle's algorithm (by  enabling TCP_NODELAY). Data will be  sent earlier, at the cost of an increase in bandwidth consumption and number  of packets.

<undefined>

http.socket.sendbuffer

Integer

The value to set on Socket.setSendBufferSize(int).  This value is a suggestion to the kernel from the application about the size  of buffers to use for the data to be sent over the socket.

<undefined>

http.socket.receivebuffer

Integer

The value to set on Socket.setReceiveBufferSize(int).  This value is a suggestion to the kernel from the application about the size  of buffers to use for the data to be received over the socket.

<undefined>

http.socket.linger

Integer

The linger time (SO_LINGER) in seconds. This option disables/enables immediate  return from a close() of a TCP Socket. Enabling this option with a non-zero  Integer timeout means that a close() will block pending the transmission and  acknowledgement of all data written to the peer, at which point the socket is  closed gracefully. Value 0 implies  that the option is disabled. Value -1 implies that the JRE default is used.

<undefined>

http.connection.timeout

Integer

The timeout until a connection is established. A value  of zero means the timeout is not used.

<undefined>

http.connection.stalecheck

Boolean

Determines whether stale connection check is to be  used. Disabling stale connection check may result in slight performance  improvement at the risk of getting an I/O error when executing a request over  a connection that has been closed at the server side.

<undefined>

 

HttpConnectionManagerParams

Applicable at thefollowing levels: global -> client -> connectionmanager

Name

Type

Description

Default

http.connection-manager.max-per-host

Map

Defines the maximum number of connections allowed per  host configuration. These values only apply to the number of connections from  a particular instance of HttpConnectionManager.

This parameter expects a value of type Map. The value should map instances of HostConfiguration to Integers. The default value can be specified  using ANY_HOST_CONFIGURATION.

<undefined>

http.connection-manager.max-total

Integer

Defines the maximum number of connections allowed  overall. This value only applies to the number of connections from a  particular instance of HttpConnectionManager.

<undefined>

 

HostParams

Applicable at thefollowing levels: global -> client -> host

Name

Type

Description

Default

http.default-headers

Collection

The request headers to be sent per default with each  request. This parameter expects a value of type Collection. The  collection is expected to contain HTTP headers

<undefined>

 

转载来源:http://www.cnblogs.com/tanhao/archive/2012/03/13/2393226.html

 

三、参数设置相关类的类图 

         HttpParams为接口,是定义组件运行时行为的一个不变的值的集合,包含简单对象:整型,浮点型,字符串,集合,还有运行时不变的对象。实现HttpParams的类或接口实现类的子类组成不同的组件,不同的组件定义了不同的行为。

 

HttpClient httpClient = new HttpClient(); 
		HttpClientParams hcp=new HttpClientParams();
		hcp.setParameter(HttpClientParams.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
		hcp.setParameter(HttpClientParams.SO_TIMEOUT, new Integer(1000));
		hcp.setParameter(HttpClientParams.HTTP_CONTENT_CHARSET, "gbk");
		httpClient.setParams(hcp);
		
		HostConfiguration hostconfig = new HostConfiguration(); 
		hostconfig.setHost("www.baidu.com"); 
		hostconfig.getParams().setParameter(HttpClientParams.PROTOCOL_VERSION, HttpVersion.HTTP_1_0); 		 
		GetMethod httpget = new GetMethod("/"); 
		httpget.getParams().setParameter(HttpClientParams.SO_TIMEOUT, new Integer(5000)); 		 
		try {      
			httpClient.executeMethod(hostconfig, httpget);   
			System.out.println(httpget.getParams().getParameter(HttpClientParams.PROTOCOL_VERSION));   
			System.out.println(httpget.getParams().getParameter(HttpClientParams.SO_TIMEOUT));   
			System.out.println(httpget.getParams().getParameter(HttpClientParams.HTTP_CONTENT_CHARSET)); 
			} finally {   
				httpget.releaseConnection(); 
			}


 

        注:通过上图可以看到一种设计方式:  基类可以用一个HashMap存储不定量的key-value信息,在不同子类中分别定义特定的key,从而达到存储动态信息的设计。

 

 

四、HttpClient的持久化 

 

       继承实现HttpParams的各个组件与用于执行请求的HttpClient实例联系起来共同存储请求响应的状态,从而实现HttpClient的持久化状态,在HttpClient类源码中主要通过以下属性维护持久化状态。

  // ----------------------------------------------------- Instance Variables

    /** 
     * The {@link HttpConnectionManager connection manager} being used to manage
     * connections for this HttpClient
     */
    private HttpConnectionManager httpConnectionManager;

    /**
     * The {@link HttpState HTTP state} associated with this HttpClient.
     */
    private HttpState state = new HttpState();
    
    /**
     * The {@link HttpClientParams collection of parameters} associated with this HttpClient.
     */
    private HttpClientParams params = null; 

    /** 
     * The {@link HostConfiguration host configuration} associated with
     * the HttpClient
     */
    private HostConfiguration hostConfiguration = new HostConfiguration();
    

 

    下面我们看一下各个属性的实例化顺序。

    首先我们可以写个测试类:

public class Test {
	public static void main(String[] args) throws HttpException, IOException {
		HttpClient httpClient=new HttpClient();
		String url="http://www.baidu.com/s?ie=utf8&oe=utf8&wd=%E8%B0%B7%E6%AD%8C%E7%BF%BB%E8%AF%91&tn=98010089_dg";
		GetMethod getMethod=new GetMethod(url);
		httpClient.executeMethod(getMethod);
		String htmlText=getMethod.getResponseBodyAsString();
		System.out.println(htmlText);
	}
}

1、实例化HttpClientParams对象

     通过查看可以发现,HttpClient实例化后如果未设置HttpClientParams,则实例化HttpClientParams并调用其父类构造方法,进而执行类DefaultHttpParamsFactorygetDefaultParams()方法。

 /* (non-Javadoc)
     * @see org.apache.commons.httpclient.params.HttpParamsFactory#getDefaultParams()
     */
    public synchronized HttpParams getDefaultParams() {
        if (httpParams == null) {
            httpParams = createParams();
        }

        return httpParams;
    }

    protected HttpParams createParams() {
        HttpClientParams params = new HttpClientParams(null);
        
        params.setParameter(HttpMethodParams.USER_AGENT, "Jakarta Commons-HttpClient/3.1");
        params.setVersion(HttpVersion.HTTP_1_1);
        params.setConnectionManagerClass(SimpleHttpConnectionManager.class);
        params.setCookiePolicy(CookiePolicy.DEFAULT);
        params.setHttpElementCharset("US-ASCII");
        params.setContentCharset("ISO-8859-1");
        params.setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler());
        
        ArrayList datePatterns = new ArrayList();
        datePatterns.addAll(
            Arrays.asList(
                new String[] {
                    DateUtil.PATTERN_RFC1123,
                    DateUtil.PATTERN_RFC1036,
                    DateUtil.PATTERN_ASCTIME,
                    "EEE, dd-MMM-yyyy HH:mm:ss z",
                    "EEE, dd-MMM-yyyy HH-mm-ss z",
                    "EEE, dd MMM yy HH:mm:ss z",
                    "EEE dd-MMM-yyyy HH:mm:ss z",
                    "EEE dd MMM yyyy HH:mm:ss z",
                    "EEE dd-MMM-yyyy HH-mm-ss z",
                    "EEE dd-MMM-yy HH:mm:ss z",
                    "EEE dd MMM yy HH:mm:ss z",
                    "EEE,dd-MMM-yy HH:mm:ss z",
                    "EEE,dd-MMM-yyyy HH:mm:ss z",
                    "EEE, dd-MM-yyyy HH:mm:ss z",                
                }
            )
        );
        params.setParameter(HttpMethodParams.DATE_PATTERNS, datePatterns);
            
        // TODO: To be removed. Provided for backward compatibility
        String agent = null;
        try {
            agent = System.getProperty("httpclient.useragent");
        } catch (SecurityException ignore) {
        }
        if (agent != null) {        
            params.setParameter(HttpMethodParams.USER_AGENT, agent);
        }
        
        // TODO: To be removed. Provided for backward compatibility
        String preemptiveDefault = null;
        try {
            preemptiveDefault = System.getProperty("httpclient.authentication.preemptive");
        } catch (SecurityException ignore) {
        }
        if (preemptiveDefault != null) {
            preemptiveDefault = preemptiveDefault.trim().toLowerCase();
            if (preemptiveDefault.equals("true")) {
                params.setParameter(HttpClientParams.PREEMPTIVE_AUTHENTICATION, Boolean.TRUE);
            } else if (preemptiveDefault.equals("false")) {
                params.setParameter(HttpClientParams.PREEMPTIVE_AUTHENTICATION, Boolean.FALSE);
            }
        }
        
        // TODO: To be removed. Provided for backward compatibility
        String defaultCookiePolicy = null;
        try {
            defaultCookiePolicy = System.getProperty("apache.commons.httpclient.cookiespec");
        } catch (SecurityException ignore) {
        }
        if (defaultCookiePolicy != null) {
            if ("COMPATIBILITY".equalsIgnoreCase(defaultCookiePolicy)) {
                params.setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);
            } else if ("NETSCAPE_DRAFT".equalsIgnoreCase(defaultCookiePolicy)) {
                params.setCookiePolicy(CookiePolicy.NETSCAPE);
            } else if ("RFC2109".equalsIgnoreCase(defaultCookiePolicy)) {
                params.setCookiePolicy(CookiePolicy.RFC_2109);
            }
        }

        return params;
    } 


 

2、实例化HttpConnectionManager对象

   若未单独设置HttpConnectionManager,则在构造函数中使用SimpleHttpConnectionManager类设置默认HttpConnectionManager对象

/**
     * Creates an instance of HttpClient using the given 
     * {@link HttpClientParams parameter set}.
     * 
     * @param params The {@link HttpClientParams parameters} to use.
     * 
     * @see HttpClientParams
     * 
     * @since 3.0
     */
    public HttpClient(HttpClientParams params) {
        super();
        if (params == null) {
            throw new IllegalArgumentException("Params may not be null");  
        }
        this.params = params;
        this.httpConnectionManager = null;
        Class clazz = params.getConnectionManagerClass();
        if (clazz != null) {
            try {
                this.httpConnectionManager = (HttpConnectionManager) clazz.newInstance();
            } catch (Exception e) {
                LOG.warn("Error instantiating connection manager class, defaulting to"
                    + " SimpleHttpConnectionManager", 
                    e);
            }
        }
        if (this.httpConnectionManager == null) {
            this.httpConnectionManager = new SimpleHttpConnectionManager();
        }
        if (this.httpConnectionManager != null) {
            this.httpConnectionManager.getParams().setDefaults(this.params);
        }
    }

3、实例化HostConfiguration对象(HostParams params= hostConfiguration.getParams() )。

   在发送请求前实例化HostConfiguration对象,过程为:实例化HttpMethod->获得HttpMethodURI->实例化HostConfiguration。

/**
     * Executes the given {@link HttpMethod HTTP method} using the given custom 
     * {@link HostConfiguration host configuration} with the given custom 
     * {@link HttpState HTTP state}.
     *
     * @param hostconfig The {@link HostConfiguration host configuration} to use.
     * If <code>null</code>, the host configuration returned by {@link #getHostConfiguration} will be used.
     * @param method the {@link HttpMethod HTTP method} to execute.
     * @param state the {@link HttpState HTTP state} to use when executing the method.
     * If <code>null</code>, the state returned by {@link #getState} will be used.
     *
     * @return the method's response code
     *
     * @throws IOException If an I/O (transport) error occurs. Some transport exceptions
     *                     can be recovered from.
     * @throws HttpException  If a protocol exception occurs. Usually protocol exceptions 
     *                    cannot be recovered from.
     * @since 2.0
     */
    public int executeMethod(HostConfiguration hostconfig, 
        final HttpMethod method, final HttpState state)
        throws IOException, HttpException  {
            
        LOG.trace("enter HttpClient.executeMethod(HostConfiguration,HttpMethod,HttpState)");

        if (method == null) {
            throw new IllegalArgumentException("HttpMethod parameter may not be null");
        }
        HostConfiguration defaulthostconfig = getHostConfiguration();
        if (hostconfig == null) {
            hostconfig = defaulthostconfig;
        }
        URI uri = method.getURI(); 
        if (hostconfig == defaulthostconfig || uri.isAbsoluteURI()) {
            // make a deep copy of the host defaults
            hostconfig = (HostConfiguration) hostconfig.clone();
            if (uri.isAbsoluteURI()) {
                hostconfig.setHost(uri);//通过URI的实例化设置设置HostConfiguration
            }
        }
        
        HttpMethodDirector methodDirector = new HttpMethodDirector(
                getHttpConnectionManager(),
                hostconfig,
                this.params,
                (state == null ? getState() : state));
        methodDirector.executeMethod(method);
        return method.getStatusCode();
    }

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值