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?
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);
来源:https://stackoverflow.com/questions/9379768/access-all-entries-of-httpparams