Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> 關於Android編程 >> Android POST GET請求

Android POST GET請求

編輯:關於Android編程

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. namespace Home\Controller;
  2. use Think\Controller;
  3. class AndroidController extends Controller {
  4. public function index()
  5. {
  6. //獲取賬號密碼
  7. $id=I('username');
  8. $pwd=I('password');
  9. $User=M('user');
  10. //查詢數據庫
  11. $data = $User->where("NAME='$id' AND PASSWORD='$pwd' ")->find();
  12. //登入成功
  13. if($data)
  14. {
  15. $response = array('success' => true,'msg'=>'登入成功');
  16.  
  17. $response=json_encode($response);
  18. echo $response;//返回json格式
  19. }
  20. //登入失敗
  21. else
  22. {
  23. $response = array('success' => false,'msg'=>'賬號或密碼錯誤');
  24. $response=json_encode($response);
  25. echo $response;//返回json格式
  26. }
  27. }
  28.  
  29. } 復制代碼 記得添加網絡權限 Android的網絡請求主要使用java.net包中的HttpURLConnection類,服務器與Android客戶端數據交互格式為json 1.利用POST請求方式來實現人員登入。
    1. package com.dream.apm;
    2.  
    3. import android.app.Activity;
    4. import android.content.pm.ActivityInfo;
    5. import android.os.Bundle;
    6. import android.os.Handler;
    7. import android.os.Looper;
    8. import android.os.Message;
    9. import android.view.View;
    10. import android.view.Window;
    11. import android.view.WindowManager;
    12. import android.widget.Button;
    13. import android.widget.EditText;
    14. import android.widget.LinearLayout;
    15. import android.widget.Toast;
    16. import org.json.JSONArray;
    17. import org.json.JSONException;
    18. import org.json.JSONObject;
    19.  
    20. import java.io.*;
    21. import java.net.HttpURLConnection;
    22. import java.net.MalformedURLException;
    23. import java.net.URL;
    24. import java.net.URLEncoder;
    25.  
    26. public class MyActivity extends Activity {
    27.  
    28. //請求地址
    29. private static String url="http://10.0.2.2:8080/think/index.php/Home/Android";
    30. public Button start;
    31.  
    32. public EditText username,password;
    33.  
    34. public URL http_url;
    35.  
    36. public String data;
    37.  
    38. public Handler handler;
    39.  
    40. @Override
    41. public void onCreate(Bundle savedInstanceState){
    42. super.onCreate(savedInstanceState);
    43. //設置全屏
    44. getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
    45. WindowManager.LayoutParams.FLAG_FULLSCREEN);
    46. //去除應用程序標題
    47. this.requestWindowFeature(Window.FEATURE_NO_TITLE);
    48. //設置豎屏
    49. setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
    50. setContentView(R.layout.main);
    51.  
    52. start=(Button)findViewById(R.id.start_one);
    53. username=(EditText)findViewById(R.id.username);
    54. password=(EditText)findViewById(R.id.password);
    55. //消息處理器
    56.  
    57. handler=new Handler(Looper.getMainLooper())
    58. {
    59. @Override
    60. public void handleMessage(Message msg)
    61. {
    62. super.handleMessage(msg);
    63. switch(msg.what)
    64. {
    65. //登入成功
    66. case 1:
    67. Toast.makeText(MyActivity.this, msg.getData().getString("msg"),
    68. Toast.LENGTH_SHORT).show();
    69. break;
    70. //登入失敗
    71. case 2:
    72. Toast.makeText(MyActivity.this, msg.getData().getString("msg"),
    73. Toast.LENGTH_SHORT).show();
    74. break;
    75.  
    76. }
    77. }
    78. };
    79.  
    80. start.setOnClickListener(new View.OnClickListener() {
    81. @Override
    82. public void onClick(View v) {
    83. //是否輸入賬號密碼
    84. if(username.getText().toString().length()>0&&password.getText().toString().length()>0){
    85. //子線程可以獲取UI的值,不能更改
    86. new Thread(new Runnable() {
    87. @Override
    88. public void run() {
    89. try {
    90. http_url=new URL(url);
    91. if(http_url!=null)
    92. {
    93. //打開一個HttpURLConnection連接
    94. HttpURLConnection conn = (HttpURLConnection) http_url.openConnection();
    95. conn.setConnectTimeout(5* 1000);//設置連接超時
    96. conn.setRequestMethod("POST");//以get方式發起請求
    97. //允許輸入輸出流
    98. conn.setDoInput(true);
    99. conn.setDoOutput(true);
    100. conn.setUseCaches(false);//使用Post方式不能使用緩存
    101. //獲取賬號密碼
    102. String params = "username=" + username.getText().toString()
    103. + "&password=" + password.getText().toString();
    104. //設置請求體的類型是文本類型
    105. conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
    106. //設置請求體的長度--字節長度
    107. conn.setRequestProperty("Content-Length",String.valueOf(params.getBytes().length) );
    108. //發送post參數
    109. BufferedWriter bw=new BufferedWriter(new OutputStreamWriter(conn.getOutputStream()));
    110. bw.write(params);
    111. bw.close();
    112. //接收服務器響應
    113. if (conn.getResponseCode() == 200) {
    114. InputStream is = conn.getInputStream();//得到網絡返回的輸入流
    115. BufferedReader buf=new BufferedReader(new InputStreamReader(is));//轉化為字符緩沖流
    116. data=buf.readLine();
    117. buf.close();is.close();
    118. //判斷登入結果
    119. analyse(data);
    120. }
    121. }
    122. } catch( Exception e) {
    123. e.printStackTrace();
    124. }
    125. }
    126. }).start();
    127. }
    128. else
    129. {
    130. Toast.makeText(MyActivity.this, "請完整輸入賬號密碼",
    131. Toast.LENGTH_SHORT).show();
    132. }
    133. }
    134. });
    135. }
    136.  
    137. public void analyse (String data)
    138. {
    139. System.out.println(data);
    140. try {
    141. JSONObject json_data=new JSONObject(data);
    142. Boolean state=json_data.getBoolean("success");
    143. String msg=json_data.getString("msg");
    144. //登入成功
    145. if(state)
    146. {
    147. //發送消息
    148. Message message= new Message();
    149. message.what=1;
    150. Bundle temp = new Bundle();
    151. temp.putString("msg",msg);
    152. message.setData(temp);
    153. handler.sendMessage(message);
    154.  
    155. }
    156. //登入失敗
    157. else
    158. {
    159. Message message= new Message();
    160. message.what=2;
    161. Bundle temp = new Bundle();
    162. temp.putString("msg",msg);
    163. message.setData(temp);
    164. handler.sendMessage(message);
    165. }
    166. } catch (JSONException e) {
    167. e.printStackTrace();
    168. }
    169. }
    170. } 復制代碼 2.利用GET請求方式來實現人員登入
      1. package com.dream.apm;
      2.  
      3. import android.app.Activity;
      4. import android.content.pm.ActivityInfo;
      5. import android.os.Bundle;
      6. import android.os.Handler;
      7. import android.os.Looper;
      8. import android.os.Message;
      9. import android.view.View;
      10. import android.view.Window;
      11. import android.view.WindowManager;
      12. import android.widget.Button;
      13. import android.widget.EditText;
      14. import android.widget.LinearLayout;
      15. import android.widget.Toast;
      16. import org.json.JSONArray;
      17. import org.json.JSONException;
      18. import org.json.JSONObject;
      19.  
      20. import java.io.*;
      21. import java.net.HttpURLConnection;
      22. import java.net.MalformedURLException;
      23. import java.net.URL;
      24. import java.net.URLEncoder;
      25.  
      26. public class MyActivity extends Activity {
      27.  
      28. public Button start;
      29.  
      30. public EditText username,password;
      31.  
      32. public URL http_url;
      33.  
      34. public String data;
      35.  
      36. public Handler handler;
      37.  
      38. @Override
      39. public void onCreate(Bundle savedInstanceState){
      40. super.onCreate(savedInstanceState);
      41. //設置全屏
      42. getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
      43. WindowManager.LayoutParams.FLAG_FULLSCREEN);
      44. //去除應用程序標題
      45. this.requestWindowFeature(Window.FEATURE_NO_TITLE);
      46. //設置豎屏
      47. setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
      48. setContentView(R.layout.main);
      49.  
      50. start=(Button)findViewById(R.id.start_one);
      51. username=(EditText)findViewById(R.id.username);
      52. password=(EditText)findViewById(R.id.password);
      53. //消息處理器
      54.  
      55. handler=new Handler(Looper.getMainLooper())
      56. {
      57. @Override
      58. public void handleMessage(Message msg)
      59. {
      60. super.handleMessage(msg);
      61. switch(msg.what)
      62. {
      63. //登入成功
      64. case 1:
      65. Toast.makeText(MyActivity.this, msg.getData().getString("msg"),
      66. Toast.LENGTH_SHORT).show();
      67. break;
      68. //登入失敗
      69. case 2:
      70. Toast.makeText(MyActivity.this, msg.getData().getString("msg"),
      71. Toast.LENGTH_SHORT).show();
      72. break;
      73.  
      74. }
      75. }
      76. };
      77.  
      78. start.setOnClickListener(new View.OnClickListener() {
      79. @Override
      80. public void onClick(View v) {
      81. //是否輸入賬號密碼
      82. if(username.getText().toString().length()>0&&password.getText().toString().length()>0){
      83. //子線程可以獲取UI的值,不能更改
      84. new Thread(new Runnable() {
      85. @Override
      86. public void run() {
      87. try {
      88. //請求地址--
      89. String url="http://10.0.2.2:8080/think/index.php/Home/Android?"+ "username=" + URLEncoder.encode(username.getText().toString(), "UTF-8")
      90. + "&password=" + URLEncoder.encode(password.getText().toString(), "UTF-8");
      91. http_url=new URL(url);
      92. if(http_url!=null)
      93. {
      94. //打開一個HttpURLConnection連接
      95. HttpURLConnection conn = (HttpURLConnection) http_url.openConnection();
      96. conn.setConnectTimeout(5* 1000);//設置連接超時
      97. conn.setRequestMethod("GET");//以get方式發起請求
      98. //允許輸入流
      99. conn.setDoInput(true);
      100. //接收服務器響應
      101. if (conn.getResponseCode() == 200) {
      102. InputStream is = conn.getInputStream();//得到網絡返回的輸入流
      103. BufferedReader buf=new BufferedReader(new InputStreamReader(is));//轉化為字符緩沖流
      104. data=buf.readLine();
      105. buf.close();is.close();
      106. //判斷登入結果
      107. analyse(data);
      108. }
      109. }
      110. } catch( Exception e) {
      111. e.printStackTrace();
      112. }
      113. }
      114. }).start();
      115. }
      116. else
      117. {
      118. Toast.makeText(MyActivity.this, "請完整輸入賬號密碼",
      119. Toast.LENGTH_SHORT).show();
      120. }
      121. }
      122. });
      123. }
      124.  
      125. public void analyse (String data)
      126. {
      127. System.out.println(data);
      128. try {
      129. JSONObject json_data=new JSONObject(data);
      130. Boolean state=json_data.getBoolean("success");
      131. String msg=json_data.getString("msg");
      132. //登入成功
      133. if(state)
      134. {
      135. //發送消息
      136. Message message= new Message();
      137. message.what=1;
      138. Bundle temp = new Bundle();
      139. temp.putString("msg",msg);
      140. message.setData(temp);
      141. handler.sendMessage(message);
      142.  
      143. }
      144. //登入失敗
      145. else
      146. {
      147. Message message= new Message();
      148. message.what=2;
      149. Bundle temp = new Bundle();
      150. temp.putString("msg",msg);
      151. message.setData(temp);
      152. handler.sendMessage(message);
      153. }
      154. } catch (JSONException e) {
      155. e.printStackTrace();
      156. }
      157. }
      158. } 復制代碼 運行結果:
        \


        \
  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved