Access all entries of HttpParams

我怕爱的太早我们不能终老 提交于 2019-12-01 23:07:58

Your HttpParams is used to create HttpEntity set on HttpEntityEnclosedRequestBase object and you can then have a List back using the following code

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

If you know there's a HashMap inside, and you really need to get those params, you can always force your way in using reflection.

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"); 
}

I wanted to finish building your solution to view all HttpParams via a cast to BasicHttpParams

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

I just use this to set the Params:

HttpGet get = new HttpGet(url);
get.setHeader("Content-Type", "text/html");
get.getParams().setParameter("http.socket.timeout",20000);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!