Access all entries of HttpParams

牧云@^-^@ 提交于 2019-12-02 01:06:52

问题


Is there a way of iterating over all entries of an HttpParams object?

Someone else had a similar problem ( Print contents of HttpParams / HttpUriRequest? ) but the answers don't really work.

When looking into BasicHttpParams I see that there is a HashMap inside, but no way of accessing it directly. Also AbstractHttpParams doesn't provide any direct access to all entries.

Since I cannot rely on predefined key names the ideal way would be to iterate just over all entries HttpParams encapsulates. Or at least get a list of key names. What am I missing?


回答1:


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



回答2:


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



回答3:


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



回答4:


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


来源:https://stackoverflow.com/questions/9379768/access-all-entries-of-httpparams

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!