2012-01-05 37 views
0

在Java類中,我使用一個ArrayList說包含所有已reportid我想添加到的NameValuePair和發送HTTP的PostMethod呼叫到一個特定的報告,REPORTNAME,REPORTTYPE等列表報告網址。的Java的ArrayList到名稱值對

我想將arraylist-reportname添加到名稱值對(org.apache.commons.httpclient.NameValuePair)中,然後使用http客戶端post方法將名稱值對數據提交給特定的url。

這裏是我的名字值對

if (validateRequest()) { 
     NameValuePair[] data = { 
      new NameValuePair("first_name", firstName), 
      new NameValuePair("last_name", lastName), 
      new NameValuePair("email", mvrUser.getEmail()), 
      new NameValuePair("organization", mvrUser.getOrganization()), 
      new NameValuePair("phone", mvrUser.getPhone()), 
      new NameValuePair("website", mvrUser.getWebsite()), 
      new NameValuePair("city", mvrUser.getCity()), 
      new NameValuePair("state", mvrUser.getState()), 
      new NameValuePair("country", mvrUser.getCountry()), 
      new NameValuePair(**"report(s)", reports**.) 
     }; 

請建議我如何添加報告ArrayList中REPORTNAME到的NameValuePair的報道領域。

- 感謝

@ ADARSH 我可以使用泛型像這樣使用?

reportname = ""; 
for (GSReport report : reports) { 
     reportname = reportname + report.getReportName(); 
     reportname += ","; 
    } 

,然後在namevalue對添加的

new NameValuePair("report(s)", reportname) 
+0

當然,您可以但我只使用索引for循環刪除尾隨'|'分隔符。爲了簡單起見,我向您展示了字符串連接方法。如果列表中有許多項目,我強烈建議您更改爲'StringBuilder'。 – adarshr 2012-01-05 10:51:15

+0

爲了從arraylist中形成一個分隔的字符串列表,只需使用org.apache.commons.lang.StringUtils.join(Collection,char)..從apache common lang項目中。另外,請確保您選擇了未在報告列表中的任何字符串中使用的分隔符。 – sethu 2012-01-05 11:26:13

回答

0

嗯,你不能這樣做。 NameValuePair需要在構造函數中使用String參數。它用於HTTP POST是有意義的。

你所能做的就是拿出一個辦法來序列化對象Report轉換成String發送此字符串作爲字符串參數。這樣做的一種方法可能是劃分Report類的參數。

reports=reportName1|reportName2|reportName3

假設reports是你ArrayList

String reportsStr = ""; 

for(int i = 0; i < reports.size(); i++) { 
    reportStr += reportName; 
    if(i != reports.size() - 1) { 
     reportsStr += "|"; 
    } 
} 

NameValuePair nvPair = new NameValuePair("reports", reportsStr); 
1

的名稱值對使用地圖類的東西...如。 Hastable(它是同步的),你可以使用其他的 執行Map不同步。

1

我建議你的序列化報告ArrayList成JSON格式String

new NameValuePair("reports", reportsAsJson) 

你可以使用任何的JSON序列化圖書館的建立你reportsAsJson變量(如一個在http://json.org/java/)。它將近似地採用這種格式:

reportsAsJson = "[{reportid:'1',reportname:'First Report',reporttype:'Type 1'}, {reportid:'2',reportname:'Seond Report',reporttype:'Type 2'}]";