2012-02-21 62 views
2

是否有一種迭代HttpParams對象的所有條目的方法?訪問HttpParams的所有條目

其他人也有類似的問題(Print contents of HttpParams/HttpUriRequest?)但答案並不真正起作用。

當調查BasicHttpParams時,我發現裏面有一個HashMap,但沒有辦法直接訪問它。 AbstractHttpParams 不提供任何直接訪問所有條目。

由於我不能依賴預定義的鍵名,理想的方法是遍歷所有條目HttpParams封裝。或者至少獲得關鍵名稱列表。我錯過了什麼?

回答

4

你的HttpParams用於創建HttpEntity HttpEntityEnclosedRequestBase對象上設置,然後你可以有一個列表返回使用下面的代碼

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

我做了一個類似的事情,只是爲了從URI獲取參數(這是一個Groovy片段,在Java中也是如此): 'def uri = new URI(「https://www.yahoo.com?foo =「bar」) List parameters = new ArrayList (URLEncodedUtils.parse(uri,「UTF-8」)); parameters.each {參數 - > println parameter.name +「:」+ parameter.value}' 這是一種體面的方式來解構請求的參數,而不會搞亂HttpParams對象,除非你準確的知道你想要什麼。 – 2012-11-01 19:16:21

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

我以某種方式假定除了使用反射之外,還必須有其他方法。是不是'HttpParams'對象在'HttpClient'中的某個地方被處理了,爲了準備HTTP請求,它需要被剝離? – Brian 2012-02-21 15:32:08

-1

我只是用它來設置PARAMS:

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

但我想讀取'HttpRequest'中的所有參數。所以堅持你的例子,從'get.getParams()'得到一個列表。 – Brian 2012-03-02 07:36:21