2012-02-21 67 views
2

是否有一种迭代HttpParams对象的所有条目的方法?访问HttpParams的所有条目

其他人也有类似的问题(Print contents of HttpParams/HttpUriRequest?)但答案并不真正起作用。

当调查BasicHttpParams时,我发现里面有一个HashMap,但没有办法直接访问它。 AbstractHttpParams 不提供任何直接访问所有条目。

由于我不能依赖预定义的键名,理想的方法是遍历所有条目HttpParams封装。或者至少获得关键名称列表。我错过了什么?

回答

4

你的HttpParams用于创建HttpEntity HttpEntityEnclosedRequestBase对象上设置,然后你可以有一个列表返回使用下面的代码

final HttpPost httpPost = new HttpPost("http://..."); 

final ArrayList<NameValuePair> params = new ArrayList<NameValuePair>(); 
params.add(new BasicNameValuePair("a_param", username)); 
params.add(new BasicNameValuePair("a_second_param", password)); 

// add the parameters to the httpPost 
HttpEntity entity; 
try 
{ 
    entity = new UrlEncodedFormEntity(params); 
    httpPost.setEntity(entity); 
} 
catch (final UnsupportedEncodingException e) 
{ 
    // this should never happen. 
    throw new IllegalStateException(e); 
} 
HttpEntity httpEntity = httpPost.getEntity(); 

try 
{ 
    List<NameValuePair> parameters = new ArrayList<NameValuePair>(URLEncodedUtils.parse(httpEntity)); 
} 
catch (IOException e) 
{ 
} 
+0

我做了一个类似的事情,只是为了从URI获取参数(这是一个Groovy片段,在Java中也是如此): 'def uri = new URI(“https://www.yahoo.com?foo =“bar”) List parameters = new ArrayList (URLEncodedUtils.parse(uri,“UTF-8”)); parameters.each {参数 - > println parameter.name +“:”+ parameter.value}' 这是一种体面的方式来解构请求的参数,而不会搞乱HttpParams对象,除非你准确的知道你想要什么。 – 2012-11-01 19:16:21

2

如果你知道里面有一个HashMap,而且你确实需要得到那些参数,那么你总是可以用你的方式来使用反射。

Class clazz = httpParams.getClass(); 

Field fields[] = clazz.getDeclaredFields(); 
System.out.println("Access all the fields"); 
for (int i = 0; i < fields.length; i++){ 
    System.out.println("Field Name: " + fields[i].getName()); 
    fields[i].setAccessible(true); 
    System.out.println(fields[i].get(httpParams) + "\n"); 
} 
+0

我以某种方式假定除了使用反射之外,还必须有其他方法。是不是'HttpParams'对象在'HttpClient'中的某个地方被处理了,为了准备HTTP请求,它需要被剥离? – Brian 2012-02-21 15:32:08

-1

我只是用它来设置PARAMS:

HttpGet get = new HttpGet(url); 
get.setHeader("Content-Type", "text/html"); 
get.getParams().setParameter("http.socket.timeout",20000); 
+1

但我想读取'HttpRequest'中的所有参数。所以坚持你的例子,从'get.getParams()'得到一个列表。 – Brian 2012-03-02 07:36:21