HttpClient和HttpGet 参数的优先级
http://www.cnblogs.com/LBSer/p/3295584.html
一般在使用HttpClient时,我们提前设置好参数,比如超时时间(一般socket超时和连接超时)
private DefaultHttpClient createHttpClient() { //代码1
        ThreadSafeClientConnManager connectMag = new ThreadSafeClientConnManager();
        ...
        client = new DefaultHttpClient(connectMag);
        client.getParams().setParameter(CoreProtocolPNames.USER_AGENT,
                "...");
        client.getParams().setIntParameter(CoreConnectionPNames.SO_TIMEOUT,
                2000);
        client.getParams().setIntParameter(
                CoreConnectionPNames.CONNECTION_TIMEOUT, 1000);
        return client;
    }
但是我们也可以通过HttpUriRequest来设置参数,比如HttpGet、HttpPost。
httpGet.getParams().setIntParameter(
CoreConnectionPNames.SO_TIMEOUT, 5000);
httpGet.getParams().setIntParameter(
CoreConnectionPNames.CONNECTION_TIMEOUT, 5000);
httpclient.execute(httpGet, new BasicResponseHandler());
这里的问题是:当我们既在HttlClent设置了超时时间,又在HttpGet设置了超时时间,那么到底以哪个设置为准?
仔细查看代码,发现httpclient.execute最终调用了以下代码,创建了RequestDirector director,在创建director中通过determineParams(request))函数设置了参数。
public final HttpResponse execute(HttpHost target, HttpRequest request,
HttpContext context)
throws IOException, ClientProtocolException { if (request == null) {
throw new IllegalArgumentException
("Request must not be null.");
}
// a null target may be acceptable, this depends on the route planner
// a null context is acceptable, default context created below HttpContext execContext = null;
RequestDirector director = null; // Initialize the request execution context making copies of
// all shared objects that are potentially threading unsafe.
synchronized (this) { HttpContext defaultContext = createHttpContext();
if (context == null) {
execContext = defaultContext;
} else {
execContext = new DefaultedHttpContext(context, defaultContext);
}
// Create a director for this request
director = createClientRequestDirector(
getRequestExecutor(),
getConnectionManager(),
getConnectionReuseStrategy(),
getConnectionKeepAliveStrategy(),
getRoutePlanner(),
getProtocolProcessor(),
getHttpRequestRetryHandler(),
getRedirectStrategy(),
getTargetAuthenticationHandler(),
getProxyAuthenticationHandler(),
getUserTokenHandler(),
determineParams(request)); //设置了参数
} try {
return director.execute(target, request, execContext);
} catch(HttpException httpException) {
throw new ClientProtocolException(httpException);
}
}
那determineParams(request))函数干了什么呢?其实是创建了个HttpParams,也就是ClientParamsStack(ClientParamsStack extends AbstractHttpParams,而AbstractHttpParams implements HttpParams)。
ClientParamsStack拿来干什么用的呢?Represents a stack of parameter collections. When retrieving a parameter, the stack is searched in a fixed order and the first match returned. Setting parameters via the stack is not supported. To minimize overhead, the stack has a fixed size and does not maintain an internal array. The supported stack entries, sorted by increasing priority (摘自:http://hc.apache.org/httpcomponents-client-ga/httpclient/apidocs/org/apache/http/impl/client/ClientParamsStack.html)
上面大意是:ClientParamsStack是个参数栈,这个参数栈里有四个参数,参数优先级是越来越高的,i.e. applicationParams < clientParams < requestParams < overrideParams,从这里可以看出requestParams优先级比clientParams高(在本例中,requestParams是从HttpGet设置的,而clientParams是HttpClient设置的),也就是说当HttpGet和HttpClient同时设置了超时时,以HttpGet设置的为准!
protected HttpParams determineParams(HttpRequest req) {
        return new ClientParamsStack
            (null, getParams(), req.getParams(), null);
    }
public ClientParamsStack(HttpParams aparams, HttpParams cparams,
HttpParams rparams, HttpParams oparams) {
applicationParams = aparams;
clientParams = cparams;
requestParams = rparams;
overrideParams = oparams;
}
既然各个参数有优先级,那么优先级是如何实现的呢?其实原理很简单,也就是按overrideParams、requestParams、clientParams、applicationParams的顺序依次判断,如果不为空就返回。(注:getParameter()函数经常被底层实现用到)
public Object getParameter(String name) {
        if (name == null) {
            throw new IllegalArgumentException
                ("Parameter name must not be null.");
        }
        Object result = null;
        if (overrideParams != null) {
            result = overrideParams.getParameter(name);
        }
        if ((result == null) && (requestParams != null)) {
            result = requestParams.getParameter(name);
        }
        if ((result == null) && (clientParams != null)) {
            result = clientParams.getParameter(name);
        }
        if ((result == null) && (applicationParams != null)) {
            result = applicationParams.getParameter(name);
        }
        return result;
    }												
											HttpClient和HttpGet 参数的优先级的更多相关文章
- 使用httpClient调用接口,参数用map封装或者使用JSON参数,并转换返回结果
		
这里接口用表存起来,标记请求方式,然后接受参数,消息或者请求参数都可以, 然后先是遍历需要调用的接口,封装参数,再分别调用get与post即可,没有微服务还是得自己写 //消息转发-获取参数中对应参数 ...
 - httpclient提交json参数
		
private void httpReqUrl(List<HongGuTan> list, String url) throws ClientProtocolException, IOEx ...
 - provider和consumer配置参数的优先级
		
<dubbo:service>和<dubbo:reference>存在一些相同的参数,例如:timeout,retries等,那么哪个配置的优先级高呢? consumer合并u ...
 - Dubbo配置参数的优先级
		
总结为: 1).Java运行时虚拟机参数 eg:-Ddubbo.protocol.port=20880 2).dubbo.xml || application.properties(SpringBoo ...
 - HttpClient实现POST参数提交
		
HttpClient client = new HttpClient(); //使用FormUrlEncodedContent做HttpContent var content = new FormUr ...
 - new HttpClient().PostAsync封装参数
		
var data = Encoding.UTF8.GetBytes("{ \"y\": 5, \"x\": 3}"); var conten ...
 - Request.Params用法,后台接收httpget参数
		
使用Request.Params["id"]来获取参数是一种比较有效的途径. request.params其实是一个集合,它依次包括request.querystring.requ ...
 - Java HttpClient Post请求参数格式为XML
		
1.最近忙着做一个接口,拿到文档的时候,what?我当时就震惊了,全都是XML数据传输. 我当时就懵了,哎没得办法,在暑假传输这方面笔者比较熟练json格式数据,简单易懂啊 那就学呗. 2.我在使用的 ...
 - HTTPClient模块的HttpGet和HttpPost
		
HttpClient常用HttpGet和HttpPost这两个类,分别对应Get方式和Post方式. 无论是使用HttpGet,还是使用HttpPost,都必须通过如下3步来访问HTTP资源. 1.创 ...
 
随机推荐
- Linux    sort  uniq 命令。简单运用
			
-n #代表以数字方法排序,如果倒序加上-r -t ':' #-t指定分隔符-k ...
 - Useful Field of View (UFOV)
			
IE8不支持canvas,使用excanvas.js,js代码需要放在window.onload=function(){...}内,$(docuemnt).ready(function(){...}) ...
 - Ansible之ansible-playbook roles
			
刚开始学习运用 playbook 时,可能会把 playbook 写成一个很大的文件,到后来可能你会希望这些文件是可以方便去重用的,所以需要重新去组织这些文件. 基本上,使用 include 语句引用 ...
 - 自适应XAML布局经验总结 (二) 局部布局设计模式1
			
本系列对实际项目中的XAML布局场景进行总结,给出了较优化的自适应布局解决方案,希望对大家有所帮助. 下面开始介绍局部布局设计模式. 1. 工具栏模式 适用于工具栏,标题等的布局. 此块布局区域外层使 ...
 - 学习Spring Data JPA
			
简介 Spring Data 是spring的一个子项目,在官网上是这样解释的: Spring Data 是为数据访问提供一种熟悉且一致的基于Spring的编程模型,同时仍然保留底层数据存储的特殊 ...
 - ORM到底是什么有何优缺点
			
转载地址:http://www.cnblogs.com/wgbs25673578/p/5140482.html ORM的概念, ORM到底是什么 一.ORM简介 对象关系映射(Obje ...
 - Day 34 黏包
			
一.什么是粘包 须知:只有TCP有粘包现象,UDP永远不会粘包 粘包不一定会发生 如果发生了:1.可能是在客户端已经粘了 2.客户端没有粘,可能是在服务端粘了 应用程序所看到的数据是一个整体,或说是一 ...
 - leetcode 90. 子集 II JAVA
			
题目: 给定一个可能包含重复元素的整数数组 nums,返回该数组所有可能的子集(幂集). 说明:解集不能包含重复的子集. 示例: 输入: [1,2,2] 输出: [ [2], [1], [1,2,2] ...
 - jquery移动端一个按钮两个事件
			
当一个按钮已经有一个事件,如点击,弹窗显示,若还要加个事件,可以用touchstart 如: var videoCover = $("#videoCover");//视频封面 $( ...
 - Python拾遗
			
for...else...语句 用 break 关键字终止当前循环就不会执行当前的 else 语句,而使用 continue 关键字快速进入下一论循环,或者没有使用其他关键字,循环的正常结束后,就会触 ...