有没有办法遍历HttpParams
对象的所有条目?
其他人也有类似的问题(打印 HttpParams / HttpUriRequest 的内容?)但答案并没有真正起作用。
在查看BasicHttpParams时,我看到有一个HashMap
内部,但无法直接访问它。AbstractHttpParams
也不提供对所有条目的任何直接访问。
由于我不能依赖预定义的键名,理想的方法是遍历所有条目HttpParams
封装。或者至少得到一个键名列表。我错过了什么?
有没有办法遍历HttpParams
对象的所有条目?
其他人也有类似的问题(打印 HttpParams / HttpUriRequest 的内容?)但答案并没有真正起作用。
在查看BasicHttpParams时,我看到有一个HashMap
内部,但无法直接访问它。AbstractHttpParams
也不提供对所有条目的任何直接访问。
由于我不能依赖预定义的键名,理想的方法是遍历所有条目HttpParams
封装。或者至少得到一个键名列表。我错过了什么?
您的 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)
{
}
如果您知道有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");
}
我想完成构建您的解决方案以通过转换为 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));
}
我只是用它来设置参数:
HttpGet get = new HttpGet(url);
get.setHeader("Content-Type", "text/html");
get.getParams().setParameter("http.socket.timeout",20000);