[轉]Android Http get post請求

首先我們先了解下Get請求和Post請求的區別:

表單提交中get和 post方式的區別有5點:
1.get是從服務器上獲取數據,post是向服務器傳送數據。
2.get是把參數數據隊列加到提交表單的 ACTION屬性所指的URL中,值和表單內各個字段一一對應,在URL中可以看到。post是通過HTTPpost機制,將表單內各個字段與其內容放置在HTML HEADER內一起傳送到ACTION屬性所指的URL地址。用戶看不到這個過程。
3.對於get方式,服務器端用 Request.QueryString獲取變量的值,對於post方式,服務器端用Request.Form獲取提交的數據。
4.get 傳送的數據量較小,不能大於2KB。post傳送的數據量較大,一般被默認爲不受限制。但理論上,IIS4中最大量爲80KB,IIS5中爲100KB。
5.get安全性非常低,post安全性較高。

一、HttpClinet方式

1、HTTP GET 示例:

複製代碼
 1 public class TestHttpGetMethod{  
2 public void get(){
3 BufferedReader in = null;
4 try{
5 HttpClient client = new DefaultHttpClient();
6 HttpGet request = new HttpGet();
7 request.setURI("http://w26.javaeye.com");
8 HttpResponse response = client.execute(request);
9 in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
10 StringBuffer sb = new StringBuffer("");
11 String line = "";
12 String NL = System.getProperty("line.separator");
13 while((line = in.readLine()) != null){
14 sb.append(line + NL);
15
16 }
17 in.close();
18 String page = sb.toString();
19 Log.i(TAG, page);
20 }catch(Exception e){
21 Log.e(TAG,e.toString())
22 }finally{
23 if(in != null){
24 try{
25 in.close();
26 }catch(IOException ioe){
27 Log.e(TAG, ioe.toString());
28 }
29 }
30 }
31 }
32 }
複製代碼


帶參數的 HTTP GET: 
HttpGet request = new HttpGet("http://www.baidu.com/s?wd=amos_tl");  
client.execute(request);

2、HTTP POST 示例:

複製代碼
 1 public class TestHttpPostMethod{  
2 public void post(){
3 BufferedReader in = null;
4 try{
5 HttpClient client = new DefaultHttpClient();
6 HttpPost request = new HttpPost("http://localhost/upload.jsp");
7 List<NameValuePair> postParams = new ArrayList<NameValuePair>();
8 postParams.add(new BasicNameValuePair("filename", "sex.mov"));
9 UrlEncodeFormEntity formEntity = new UrlEncodeFormEntity(postParams);
10 request.setEntity(formEntity);
11 HttpResponse response = client.execute(request);
12 in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
13 StringBuffer sb = new StringBuffer("");
14 String line = "";
15 String NL = System.getProperty("line.separator");
16 while((line = in.readLine()) != null){
17 sb.append(line + NL);
18 }
19 in.close();
20 String result = sb.toString();
21 Log.i(TAG, result );
22 }catch(Exception e){
23 Log.e(TAG,e.toString())
24 }finally{
25 if(in != null){
26 try{
27 in.close();
28 }catch(IOException ioe){
29 Log.e(TAG, ioe.toString());
30 }
31 }
32 }
33 }
34 }
複製代碼


二、HttpURLConnection 方式

複製代碼
 1 URL url = null;
2 HttpURLConnection conn = null;
3 InputStream in = null;
4 OutputStream out = null;
5 byte[] data ="測試字符串".getBytes();
6 try{
7 url =new URL("www.xxx.com/servlet");
8 conn = (HttpURLConnection) url.openConnection();
9
10 //設置連接屬性
11 conn.setDoOutput(true);// 使用 URL 連接進行輸出
12 conn.setDoInput(true);// 使用 URL 連接進行輸入
13 conn.setUseCaches(false);// 忽略緩存
14 conn.setConnectTimeout(30000);//設置連接超時時長,單位毫秒
15 conn.setRequestMethod("POST");//設置請求方式,POST or GET,注意:如果請求地址爲一個servlet地址的話必須設置成POST方式
16
17 //設置請求頭
18 conn.setRequestProperty("Accept", "*/*");
19 conn.setRequestProperty("Connection", "Keep-Alive");
20 conn.setRequestProperty("Accept-Charset", "utf-8");
21 if (data != null) {
22 out = conn.getOutputStream();
23 out.write(data);
24 }
25 int code = conn.getResponseCode();
26 if(code ==200){
27 in = conn.getInputStream();// 可能造成阻塞
28 long len = conn.getContentLength();
29 byte[] bs = new byte[(int) len];//返回結果字節數組
30 int all = 0;
31 int dn = 0;
32 while ((dn = in.read(bs, all, 1)) > 0) {
33 all += dn;
34 if (all == len) {
35 break;
36 }
37 }
38 }
39 }
複製代碼

 

======================================

那麼接下來讓我們看看在Android平臺開發中如何執行一個Post請求:

以下是代碼示例:

複製代碼
 1 package com.jixuzou.search;
2 import java.util.ArrayList;
3 import java.util.List;
4 import org.apache.http.HttpResponse;
5 import org.apache.http.NameValuePair;
6 import org.apache.http.client.entity.UrlEncodedFormEntity;
7 import org.apache.http.client.methods.HttpPost;
8 import org.apache.http.impl.client.DefaultHttpClient;
9 import org.apache.http.message.BasicNameValuePair;
10 import org.apache.http.protocol.HTTP;
11 import org.apache.http.util.EntityUtils;
12 import android.app.Activity;
13 import android.os.Bundle;
14 import android.view.View;
15 import android.view.View.OnClickListener;
16 import android.widget.Button;
17 public class mian extends Activity {
18 /** Called when the activity is first created. */
19 private Button btnTest;
20 @Override
21 public void onCreate(Bundle savedInstanceState) {
22 super.onCreate(savedInstanceState);
23 setContentView(R.layout.main);
24 btnTest = (Button) findViewById(R.id.Button01);
25 btnTest.setOnClickListener(new OnClickListener() {
26 @Override
27 public void onClick(View v) {
28 getWeather();
29 }
30 });
31 }
32 private void getWeather(){
33 try {
34 final String SERVER_URL = "http://webservice.webxml.com.cn/WebServices/WeatherWS.asmx/getWeather"; // 定義需要獲取的內容來源地址
35 HttpPost request = new HttpPost(SERVER_URL); // 根據內容來源地址創建一個Http請求
36 List params = new ArrayList();
37 params.add(new BasicNameValuePair("theCityCode", "長沙")); // 添加必須的參數
38 params.add(new BasicNameValuePair("theUserID", "")); // 添加必須的參數
39 request.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8)); // 設置參數的編碼
40 HttpResponse httpResponse = new DefaultHttpClient().execute(request); // 發送請求並獲取反饋
41 // 解析返回的內容
42 if (httpResponse.getStatusLine().getStatusCode() != 404)
43 {
44 String result = EntityUtils.toString(httpResponse.getEntity());
45 System.out.println(result);
46 }
47 } catch (Exception e) {
48 }
49 }
50 }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章