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