TShopping

 找回密碼
 註冊
搜索
查看: 7180|回復: 0

[教學] Android之HttpPost與HttpGet使用

[複製鏈接]
發表於 2016-2-4 14:11:41 | 顯示全部樓層 |閱讀模式
 
Push to Facebook
什麼是Get?什麼是Post?

對於寫網頁程式的人來說應該是不陌生,在網頁表單中,要送出資料時就會選擇要用Get的方式還是Post的方式。常見的Get方式是在網址後面加上查詢字串,像是
http://www.myweb.com/product?p=1&a=1&b=2之類的,第一個用問號(?),之後每個都用(&)。

在Android中一樣可以用Get及Post去取得伺服器給予的資料。



在Android中使用Get及Post的幾個提示
  • 使用org.apache.http套件(也可以用別的)
  • Androidmanifest.xml中要加入存取網路的授權
  • 清楚知道要使用Get還是Post
  • 如果抓網路資料時間太久,建議把它放到背景執行並加上Loading提示


Get的使用步驟
首頁你要建立一個HttpClient 物件:
  1. HttpClient client = new DefaultHttpClient();
複製代碼


接著建立HttpGet物件並傳入網址:
  1. HttpGet get = new HttpGet(_url);
複製代碼


當HttpClient執行Get任務後,會傳回HttpResponse :
  1. HttpResponse response = client.execute(get);
複製代碼


接下來就可以取得資料實體:
  1. HttpEntity resEntity = response.getEntity();
複製代碼



你可以把它轉成字串來使用:
  1. result = EntityUtils.toString(resEntity);
複製代碼


以上就是Get的基本操作。



Post的使用步驟
一樣先建立HttpClient物件:
  1. HttpClient client = new DefaultHttpClient();
複製代碼



接著建立HttpPost物件並傳入網址 :
  1. HttpPost post = new HttpPost(_url);
複製代碼



如果有參數的話,可以這樣加入:
  1. List<NameValuePair> params = new ArrayList<NameValuePair>();
複製代碼



取得資料實體後可以轉成字串來用:
  1. HttpEntity resEntity = responsePOST.getEntity();
  2. result = EntityUtils.toString(resEntity);
複製代碼


以上是Post的操作方式。在參數的部份,接下來的範例只能加入一對(key-value),若有需要多組參數的話,要改成陣列的方式。
在Androidmanifest.xml加入網路存取權限
  1. <uses-permission android:name="android.permission.INTERNET"/>
複製代碼


在連線結束後要斷線,在 try..catch 最後增加 finally 來斷線。
  1. finally {
  2.    client.getConnectionManager().shutdown();
  3. }
複製代碼



範例程式碼
  1. package com.tonycube.demo;

  2. import java.util.ArrayList;
  3. import java.util.List;

  4. import org.apache.http.HttpEntity;
  5. import org.apache.http.HttpResponse;
  6. import org.apache.http.NameValuePair;
  7. import org.apache.http.client.HttpClient;
  8. import org.apache.http.client.entity.UrlEncodedFormEntity;
  9. import org.apache.http.client.methods.HttpGet;
  10. import org.apache.http.client.methods.HttpPost;
  11. import org.apache.http.impl.client.DefaultHttpClient;
  12. import org.apache.http.message.BasicNameValuePair;
  13. import org.apache.http.protocol.HTTP;
  14. import org.apache.http.util.EntityUtils;

  15. import android.app.Activity;
  16. import android.os.Bundle;
  17. import android.view.View;
  18. import android.view.View.OnClickListener;
  19. import android.widget.Button;
  20. import android.widget.TextView;

  21. public class GetPostDemoActivity extends Activity {
  22.    
  23.     private TextView txtResult = null;
  24.     private Button btnLoad = null;
  25.    
  26.     @Override
  27.     public void onCreate(Bundle savedInstanceState) {
  28.         super.onCreate(savedInstanceState);
  29.         setContentView(R.layout.main);
  30.         
  31.         initView();
  32.     }
  33.    
  34.    
  35.     private void loadPage() {
  36.         String html = getHtmlByGet("http://zh.wikipedia.org/wiki/Wiki");
  37.         txtResult.setText(html);
  38.     }


  39.     private void initView() {
  40.         txtResult = (TextView) findViewById(R.id.txtResult);
  41.         btnLoad = (Button) findViewById(R.id.btnLoad);
  42.         btnLoad.setOnClickListener(new OnClickListener(){

  43.             @Override
  44.             public void onClick(View v) {
  45.                 loadPage();
  46.             }
  47.             
  48.         });
  49.     }




  50.     public String getHtmlByPost(String _url, String _queryKey, String _queryValue){   
  51.         
  52.         String result = "";
  53.         
  54.         try {
  55.             HttpClient client = new DefaultHttpClient();
  56.                         
  57.             HttpPost post = new HttpPost(_url);
  58.             
  59.             //參數
  60.             if (_queryKey != ""){
  61.                 List<NameValuePair> params = new ArrayList<NameValuePair>();
  62.                 params.add(new BasicNameValuePair(_queryKey, _queryValue));
  63.                 UrlEncodedFormEntity ent = new UrlEncodedFormEntity(params, HTTP.UTF_8);
  64.                 post.setEntity(ent);
  65.             }
  66.             
  67.             HttpResponse responsePOST = client.execute(post);
  68.             
  69.             HttpEntity resEntity = responsePOST.getEntity();
  70.             
  71.             if (resEntity != null) {   
  72.                 result = EntityUtils.toString(resEntity);
  73.             }
  74.             
  75.         } catch (Exception e) {
  76.             e.printStackTrace();
  77.         } finally {
  78.      client.getConnectionManager().shutdown();
  79. }
  80.    
  81.             
  82.         return result;
  83.     }
  84.    

  85.     public String getHtmlByGet(String _url){   
  86.         
  87.         String result = "";
  88.         
  89.         try {
  90.             HttpClient client = new DefaultHttpClient();
  91.                         
  92.             HttpGet get = new HttpGet(_url);
  93.             
  94.             HttpResponse response = client.execute(get);

  95.             HttpEntity resEntity = response.getEntity();
  96.             
  97.             if (resEntity != null) {   
  98.                 result = EntityUtils.toString(resEntity);
  99.             }

  100.         } catch (Exception e) {
  101.             e.printStackTrace();
  102.         } finally {
  103.      client.getConnectionManager().shutdown();
  104. }
  105.    
  106.             
  107.         return result;
  108.         
  109.     }
  110. }
複製代碼


一)HttpGet :doGet()方法
  1.         // doGet():將參數的鍵值對附加在url後面來傳遞
  2.         public String getResultForHttpGet(String name,String pwd) throws ClientProtocolException, IOException{
  3.                  // 服務器:服務器項目:servlet名稱
  4.                 String path="http://192.168.5.21:8080/test/test" ;
  5.                 String uri =path+"?name="+name+"&pwd="+ pwd;
  6.                  // name:服務器端的用戶名,pwd:服務器端的密碼
  7.                  // 注意字符串連接時不能帶空格
  8.                
  9.                 String result ="" ;
  10.                
  11.                 HttpGet httpGet = new HttpGet(uri);
  12.                  // 取得HTTP response
  13.                 HttpResponse response= new DefaultHttpClient().execute(httpGet);
  14.                  // 若狀態碼為200
  15.                 if (response.getStatusLine().getStatusCode()==200 ){
  16.                          // 取出應答字符串
  17.                         HttpEntity entity= response.getEntity();
  18.                         result = EntityUtils.toString(entity, HTTP.UTF_8);
  19.                 }
  20.                 return result;
  21.         }
複製代碼


(二)HttpPost :doPost()方法
  1.         // doPost():將參數打包到http報頭中傳遞
  2.         public String getReultForHttpPost(String name,String pwd) throws ClientProtocolException, IOException{
  3.                  // 服務器:服務器項目:servlet名稱
  4.                 String path="http://192.168.5.21: 8080/test/test" ;
  5.                 HttpPost httpPost = new HttpPost(path);
  6.                  // 注意:httpPost方法時,傳遞變量必須用NameValuePair[]數據存儲,通過httpRequest.setEntity()方法來發出HTTP請求
  7.                 List<NameValuePair>list= new ArrayList<NameValuePair> ( );
  8.                 list.add( new BasicNameValuePair("name" , name));
  9.                 list.add( new BasicNameValuePair("pwd" , pwd));
  10.                 httpPost.setEntity( new UrlEncodedFormEntity(list,HTTP.UTF_8));
  11.                
  12.                 String result ="" ;
  13.                 // 取得HTTP response
  14.                 HttpResponse response= new DefaultHttpClient().execute(httpPost);
  15.                  // 若狀態碼為200
  16.                 if (response.getStatusLine().getStatusCode()==200 ){
  17.                          // 取出應答字符串
  18.                         HttpEntity entity= response.getEntity();
  19.                         result = EntityUtils.toString(entity, HTTP.UTF_8);
  20.                 }
  21.                 return result;
  22.         }
複製代碼


文章來源


 

臉書網友討論
*滑块验证:
您需要登錄後才可以回帖 登錄 | 註冊 |

本版積分規則



Archiver|手機版|小黑屋|免責聲明|TShopping

GMT+8, 2024-3-29 05:34 , Processed in 0.064072 second(s), 23 queries .

本論壇言論純屬發表者個人意見,與 TShopping綜合論壇 立場無關 如有意見侵犯了您的權益 請寫信聯絡我們。

Powered by Discuz! X3.2

© 2001-2013 Comsenz Inc.

快速回復 返回頂部 返回列表