天天看點

Android POST GET請求

Android應用經常會和伺服器端互動,這就需要手機用戶端發送網絡請求,下面介紹常用的兩種網絡請求方式POST,GET。首先要差別POST和GET請求

1. GET是從伺服器上擷取資料,POST是向伺服器傳送資料。

2. GET是把參數資料隊列加到送出表單的ACTION屬性所指的URL中,值和表單内各個字段一一對應,在URL中可以看到。POST是通過HTTP post機制,将表單内各個字段與其内容放置在HTML HEADER内一起傳送到ACTION屬性所指的URL位址。使用者看不到這個過程

3. GET方式送出的資料最多隻能是1024位元組,理論上POST沒有限制,可傳較大量的資料

4. GET安全性非常低,POST安全性較高。但是執行效率卻比POST方法好。

   下面分别用Post和GET方法來實作Android應用的人員登入,首先我們搭建一個伺服器,這裡我使用WAMP環境,使用ThinkPHP架構。詳細的伺服器搭建就不說了。給出主要響應代碼:

  1. <?php  
  2. namespace Home\Controller;  
  3. use Think\Controller;  
  4. class AndroidController extends Controller {  
  5.     public function index()  
  6.     {  
  7.           //擷取賬号密碼  
  8.           $id=I('username');  
  9.           $pwd=I('password');  
  10.           $User=M('user');     
  11.           //查詢資料庫  
  12.           $data = $User->where("NAME='$id'  AND PASSWORD='$pwd' ")->find();  
  13.           //登入成功  
  14.           if($data)  
  15.           {  
  16.               $response = array('success' => true,'msg'=>'登入成功');  
  17.               $response=json_encode($response);  
  18.               echo  $response;//傳回json格式  
  19.           }  
  20.           //登入失敗  
  21.           else  
  22.               $response = array('success' => false,'msg'=>'賬号或密碼錯誤');              
  23.     }  
  24. }  

複制代碼

記得添加網絡權限   

    <uses-permission android:name="android.permission.INTERNET"></uses-permission>

    Android的網絡請求主要使用java.net包中的HttpURLConnection類,伺服器與Android用戶端資料互動格式為json

1.利用POST請求方式來實作人員登入。

  1. package com.dream.apm;  
  2. import android.app.Activity;  
  3. import android.content.pm.ActivityInfo;  
  4. import android.os.Bundle;  
  5. import android.os.Handler;  
  6. import android.os.Looper;  
  7. import android.os.Message;  
  8. import android.view.View;  
  9. import android.view.Window;  
  10. import android.view.WindowManager;  
  11. import android.widget.Button;  
  12. import android.widget.EditText;  
  13. import android.widget.LinearLayout;  
  14. import android.widget.Toast;  
  15. import org.json.JSONArray;  
  16. import org.json.JSONException;  
  17. import org.json.JSONObject;  
  18. import java.io.*;  
  19. import java.net.HttpURLConnection;  
  20. import java.net.MalformedURLException;  
  21. import java.net.URL;  
  22. import java.net.URLEncoder;  
  23. public class MyActivity extends Activity {  
  24.     //請求位址  
  25.     private static String url="http://10.0.2.2:8080/think/index.php/Home/Android";  
  26.     public Button start;  
  27.     public EditText username,password;  
  28.     public URL http_url;  
  29.     public String data;  
  30.     public Handler handler;  
  31.     @Override  
  32.       public void onCreate(Bundle savedInstanceState){  
  33.         super.onCreate(savedInstanceState);  
  34.         //設定全屏  
  35.         getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,  
  36.                 WindowManager.LayoutParams.FLAG_FULLSCREEN);  
  37.         //去除應用程式标題  
  38.         this.requestWindowFeature(Window.FEATURE_NO_TITLE);  
  39.         //設定豎屏  
  40.         setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);  
  41.         setContentView(R.layout.main);  
  42.         start=(Button)findViewById(R.id.start_one);  
  43.         username=(EditText)findViewById(R.id.username);  
  44.         password=(EditText)findViewById(R.id.password);  
  45.         //消息處理器  
  46.         handler=new Handler(Looper.getMainLooper())  
  47.         {  
  48.             @Override  
  49.             public void handleMessage(Message msg)  
  50.             {  
  51.                 super.handleMessage(msg);  
  52.                 switch(msg.what)  
  53.                 {  
  54.                     //登入成功  
  55.                     case 1:  
  56.                         Toast.makeText(MyActivity.this, msg.getData().getString("msg"),  
  57.                                 Toast.LENGTH_SHORT).show();  
  58.                         break;  
  59.                     //登入失敗  
  60.                     case 2:  
  61.                 }  
  62.             }  
  63.         };  
  64.         start.setOnClickListener(new View.OnClickListener() {  
  65.             public void onClick(View v) {  
  66.                 //是否輸入賬号密碼  
  67.                 if(username.getText().toString().length()>0&&password.getText().toString().length()>0){  
  68.                     //子線程可以擷取UI的值,不能更改  
  69.                     new Thread(new Runnable() {  
  70.                         @Override  
  71.                         public void run() {  
  72.                             try {  
  73.                                 http_url=new URL(url);  
  74.                                 if(http_url!=null)  
  75.                                 {  
  76.                                     //打開一個HttpURLConnection連接配接  
  77.                                     HttpURLConnection conn = (HttpURLConnection) http_url.openConnection();  
  78.                                     conn.setConnectTimeout(5* 1000);//設定連接配接逾時  
  79.                                     conn.setRequestMethod("POST");//以get方式發起請求  
  80.                                     //允許輸入輸出流  
  81.                                     conn.setDoInput(true);  
  82.                                     conn.setDoOutput(true);  
  83.                                     conn.setUseCaches(false);//使用Post方式不能使用緩存  
  84.                                     //擷取賬号密碼  
  85.                                     String params = "username=" + username.getText().toString()  
  86.                                             + "&password=" + password.getText().toString();  
  87.                                     //設定請求體的類型是文本類型  
  88.                                     conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");  
  89.                                     //設定請求體的長度--位元組長度  
  90.                                     conn.setRequestProperty("Content-Length",String.valueOf(params.getBytes().length) );  
  91.                                     //發送post參數  
  92.                                     BufferedWriter bw=new BufferedWriter(new OutputStreamWriter(conn.getOutputStream()));  
  93.                                     bw.write(params);  
  94.                                     bw.close();  
  95.                                     //接收伺服器響應  
  96.                                     if (conn.getResponseCode() == 200) {  
  97.                                         InputStream is = conn.getInputStream();//得到網絡傳回的輸入流  
  98.                                         BufferedReader buf=new BufferedReader(new InputStreamReader(is));//轉化為字元緩沖流  
  99.                                         data=buf.readLine();  
  100.                                         buf.close();is.close();  
  101.                                         //判斷登入結果  
  102.                                         analyse(data);  
  103.                                     }  
  104.                                 }  
  105.                             } catch( Exception e) {  
  106.                                 e.printStackTrace();  
  107.                             }  
  108.                         }  
  109.                     }).start();  
  110.                 else  
  111.                     Toast.makeText(MyActivity.this, "請完整輸入賬号密碼",  
  112.                             Toast.LENGTH_SHORT).show();  
  113.         });  
  114.     public void analyse (String data)  
  115.         System.out.println(data);  
  116.         try {  
  117.             JSONObject json_data=new JSONObject(data);  
  118.             Boolean state=json_data.getBoolean("success");  
  119.             String msg=json_data.getString("msg");  
  120.             //登入成功  
  121.             if(state)  
  122.                 //發送消息  
  123.                 Message message= new Message();  
  124.                 message.what=1;  
  125.                 Bundle temp = new Bundle();  
  126.                 temp.putString("msg",msg);  
  127.                 message.setData(temp);  
  128.                 handler.sendMessage(message);  
  129.             //登入失敗  
  130.             else  
  131.                 message.what=2;  
  132.         } catch (JSONException e) {  
  133.             e.printStackTrace();  
  134.         }  
2.利用GET請求方式來實作人員登入
  1.                                 //請求位址--  
  2.                                  String url="http://10.0.2.2:8080/think/index.php/Home/Android?"+ "username=" + URLEncoder.encode(username.getText().toString(), "UTF-8")  
  3.                                         + "&password=" + URLEncoder.encode(password.getText().toString(), "UTF-8");  
  4.                                     conn.setRequestMethod("GET");//以get方式發起請求  
  5.                                     //允許輸入流  
運作結果: