2011-01-25 170 views
3
import org.apache.http.message.BasicNameValuePair; 

private String getServerData(String returnString) {    
InputStream is = null; 

String result = ""; 
//the year data to send 
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(); 
nameValuePairs.add(new BasicNameValuePair("year","1970")); 

//http post 
try{ 
     HttpClient httpclient = new DefaultHttpClient(); 
     HttpPost httppost = new HttpPost(KEY_121); 
     httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); 
     HttpResponse response = httpclient.execute(httppost); 
     HttpEntity entity = response.getEntity(); 
     is = entity.getContent(); 

}catch(Exception e){ 
     Log.e("log_tag", "Error in http connection "+e.toString()); 
} 
} 

我的問題......任何人都可以解釋我的這段代碼嗎?

是什麼BasicNameValuePair類呢?

是什麼這塊線做

httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); 

是什麼is = entity.getContent();辦?並且我可以在BasicNameValuePair類中傳遞多個值。我可以完全通過一個VO而不是這個。

像下面...

nameValuePairs.add(new BasicNameValuePair("year","1970","sas","saassa","sas","asas")); 

回答

17

BasicNameValuePair是一個對象,特別是容納數據和鍵的容器。

例如,如果你有這樣的數據:

Name: Bob 

Family name: Smith 

Date of birth: 10/03/1977 

那麼你將這個數據存儲爲:

ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(); 

nameValuePairs.add(new BasicNameValuePair("name","bob")); 

nameValuePairs.add(new BasicNameValuePair("family name","Smith")); 

.... 

正如你看你選擇的關鍵(「名稱」)和數據是存儲爲鏈接到鍵(「bob」)。這是一種數據結構,用於加速並更輕鬆地存儲這類信息。

在你需要一個工具來使用這些數據的另一端:

httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); 

這個代碼可以在4個部分可分爲:

httppost.setEntity 

那是需要一個URL作爲參數的方法,並嘗試使用HTTP Post方法從該URL檢索數據(HTML或存儲在該頁面上的內容)。

新UrlEncodedFormEntity

那是trasform關鍵數據值對通過一個HTTP服務器的東西理解的方法。

它使用約定

&key=input 

最常用的其中之一,但請記住,有更多的方式來做到這一點。

nameValuePair 

是您之前存儲的數據。在這種情況下,它在html中有可能的輸入形式,由「input name =」標記標識。作爲數據,它具有您想要賦予表單的價值。

is = entity.getContent(); 

HttpEntity是一個抽象幫助您處理可能的結果。如果網站無法訪問或連接中斷,HttpEntity會通知您。 getContent()是您使用的方法檢索Http結果的主體,即:Web服務器發回給您的html作爲輸入流。如果請求沒有成功,它會給你一個空值。

BasicNameValuePair只接受對聯,因此您必須多次投射,並且每次將其添加到數組列表中。

您不能將它轉換爲兩個以上的值,因爲它們對數據的(鍵,值)表示沒有意義。

希望它有幫助。

4

你到底在做同場「年」具有值「1970年」一個HTTP POST請求。

就像當年的網絡發佈一樣。

一個額外位: 的BasicNameValuePair看起來很恰當地命名爲:它是一種非常簡單的(基本)組的兩件事情(對)作爲formfield(名稱)及其內容(值)。

httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));將年份和1970年的組合添加到HttpPost對象,但是使用編碼(因此在那裏沒有「非法」的東西)。

+0

+1爲了準確和解釋得好。 – Mikaveli 2011-01-25 10:38:55

+0

我已更新我的問題 – theJava 2011-01-25 10:56:48

相關問題