NameValuePair
簡單名稱值對節點類型,多用於java像URL發送post請求,在發送Post請求的時候使用該list來存放參數;
BasicNameValuePair
BasicNameValuePair是實現了apache http的NameValuePair這個接口的類型;
例子:
String url="訪問網址";
HttpPost httppost=new HttpPost(url); //建立HttpPost對象
//建立一個NameValuePair數組,用於存儲傳送的數據
List<NameValuePair> params=new ArrayList<NameValuePair>();
//添加參數(這裏我們使用NameValuePair的實現類來創建對象)
params.add(new BasicNameValuePair("鍵","值"));
//設置編碼
httppost.setEntity(new UrlEncodedFormEntity(params,HTTP.UTF_8));
//發送1653Post,並返回一個HttpResponse對象
HttpResponse response=new DefaultHttpClient().execute(httppost);
實戰
public String httpPost(Map<String, String> requestParams, String urlEncode) {
HttpPost httpPost = null;
String resp = "";
try {
// 參數設置
List<NameValuePair> params = new ArrayList<NameValuePair>();
for (Map.Entry<String, String> entry : requestParams.entrySet()) {
params.add(new BasicNameValuePair((String) entry.getKey(),
(String) entry.getValue()));
}
httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params, urlEncode));
HttpResponse response = httpClient.execute(httpPost);
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode != 200)
{
return null;
}
HttpEntity httpEntity = response.getEntity();
resp = EntityUtils.toString(httpEntity);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (httpPost != null) {
httpPost.abort();
}
}
return resp;