(一)案例一
定義了一個list,該list的數據類型是NameValuePair(簡單名稱值對節點類型),這個代碼多處用於Java像url發送Post請求。在發送post請求時用該list來存放參數。發送請求的大致過程如下:
String url="http://www.baidu.com";
HttpPost httppost=new HttpPost(url); //建立HttpPost對象
List<NameValuePair> params=new ArrayList<NameValuePair>();
//建立一個NameValuePair數組,用於存儲欲傳送的參數
params.add(new BasicNameValuePair("pwd","2544"));
//添加參數
httppost.setEntity(new UrlEncodedFormEntity(params,HTTP.UTF_8));
//設置編碼
HttpResponse response=new DefaultHttpClient().execute(httppost);
//發送Post,並返回一個HttpResponse對象
(二)案例二
/**
* 獲得HttpPost對象
*
* @param url
* 請求地址
* @param params
* 請求參數
* @param encode
* 編碼方式
* @return HttpPost對象
* @throws UnsupportedEncodingException
*/
private static HttpPost getHttpPost(String url, Map<String, String> params,
String encode) throws UnsupportedEncodingException {
HttpPost httpPost = new HttpPost(url);
if (params != null) {
List<NameValuePair> form = new ArrayList<NameValuePair>();
for (String name : params.keySet()) {
form.add(new BasicNameValuePair(name, params.get(name)));
}
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(form,
encode);
httpPost.setEntity(entity);
}
return httpPost;
}
(三)總結
httpPost其實在服務端模擬瀏覽器向其它接口發送服務的,一般情況下和httpclient,或者jsonp聯合使用,可以把它理解爲瀏覽器就行了,
裏面封裝了http協議的一些東西,所以要對http協議有一定的瞭解。
轉載自:https://www.cnblogs.com/qingruihappy/p/7817958.html