访问HttpParams的所有条目

时间:2012-02-21 15:01:08

标签: java apache-httpcomponents

有没有办法迭代HttpParams对象的所有条目?

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

在查看BasicHttpParams时,我发现内部有HashMap,但无法直接访问它。另外AbstractHttpParams  不提供对所有条目的任何直接访问。

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

4 个答案:

答案 0 :(得分:4)

您的HttpParams用于在HttpEntityEnclosedRequestBase对象上创建HttpEntity,然后您可以使用以下代码返回List

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)
{
}

答案 1 :(得分: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"); 
}

答案 2 :(得分:0)

我想完成构建您的解决方案以通过强制转换为BasicHttpParams来查看所有HttpParams

HttpParams params = //Construction of params not shown

BasicHttpParams basicParams = (BasicHttpParams) params;
Set<String> keys = basicParams.getNames();

for (String key : keys) {
    System.out.println("[Key]:" + key + " [Value]:" + basicParams.getParameter(key));
}

答案 3 :(得分:-1)

我只是用它来设置Params:

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