post get請求的運用----android篇

      GET是從服務器上獲取數據,POST是向服務器傳送數據。get,post在PHP網絡編程中常常會運用到。 php

    get post請求在Android如何運用呢? html

   

  GET是把參數數據隊列加到提交表單的ACTION屬性所指的URL中,值和表單內各個字段一一對應,在URL中能夠看到。 POST是經過HTTP post機制,將表單內各個字段與其內容放置在HTML HEADER內一塊兒傳送到ACTION屬性所指的URL地址。用戶看不到這個過程
  GET方式提交的數據最多隻能是1024字節,理論上 POST沒有限制,可傳較大量的數據
  GET安全性很是低, POST安全性較高。可是執行效率卻比 POST方法好。
   next, 下面分別用Post和 GET 方法來實現 Android 應用的 人員登入 ,首先咱們搭建一個服務器,這裏我使用WAMP環境,以使用ThinkPHP框架爲例。響應代碼以下(response code)

   code: java

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

2.利用GET請求方式來實現人員登入 android

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158

package com.dream.apm;
 
import android.app.Activity;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.Toast;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
 
import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
 
public class MyActivity extends Activity {
 
    public Button start;
 
    public EditText username,password;
 
    public URL http_url;
 
    public String data;
 
    public Handler handler;
 
    @Override
      public void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        //設置全屏
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);
        //去除應用程序標題
        this.requestWindowFeature(Window.FEATURE_NO_TITLE);
        //設置豎屏
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        setContentView(R.layout.main);
 
        start=(Button)findViewById(R.id.start_one);
        username=(EditText)findViewById(R.id.username);
        password=(EditText)findViewById(R.id.password);
        //消息處理器
 
        handler=new Handler(Looper.getMainLooper())
        {
            @Override
            public void handleMessage(Message msg)
            {
                super.handleMessage(msg);
                switch(msg.what)
                {
                    //登入成功
                    case 1:
                        Toast.makeText(MyActivity.this, msg.getData().getString("msg"),
                                Toast.LENGTH_SHORT).show();
                        break;
                    //登入失敗
                    case 2:
                        Toast.makeText(MyActivity.this, msg.getData().getString("msg"),
                                Toast.LENGTH_SHORT).show();
                        break;
 
                }
            }
        };
 
        start.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //是否輸入帳號密碼
                if(username.getText().toString().length()>0&&password.getText().toString().length()>0){
                    //子線程能夠獲取UI的值,不能更改
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            try {
                                //請求地址--
                                 String url=" http://10.0.2.2:8080/think/index.php/Home/<a title="Android" href=" http://www.android-study.com/wangluobiancheng/628.html">Android</a>?"+"username=" + URLEncoder.encode(username.getText().toString(), "UTF-8")
                                        + "&password=" + URLEncoder.encode(password.getText().toString(), "UTF-8");
                                http_url=new URL(url);
                                if(http_url!=null)
                                {
                                    //打開一個HttpURLConnection鏈接
                                    HttpURLConnection conn = (HttpURLConnection) http_url.openConnection();
                                    conn.setConnectTimeout(5* 1000);//設置鏈接超時
                                    conn.setRequestMethod("<a title="GET" href="http://www.android-study.com/wangluobiancheng/628.html">GET</a>");//以get方式發起請求
                                    //容許輸入流
                                    conn.setDoInput(true);
                                    //接收服務器響應
                                    if (conn.getResponseCode() == 200) {
                                        InputStream is = conn.getInputStream();//獲得網絡返回的輸入流
                                        BufferedReader buf=new BufferedReader(newInputStreamReader(is));//轉化爲字符緩衝流
                                        data=buf.readLine();
                                        buf.close();is.close();
                                        //判斷登入結果
                                        analyse(data);
                                    }
                                }
                            } catch( Exception e) {
                                e.printStackTrace();
                            }
                        }
                    }).start();
                }
                else
                {
                    Toast.makeText(MyActivity.this, "請完整輸入帳號密碼",
                            Toast.LENGTH_SHORT).show();
                }
            }
        });
    }
 
    public void analyse (String data)
    {
        System.out.println(data);
        try {
            JSONObject json_data=new JSONObject(data);
            Boolean state=json_data.getBoolean("success");
            String msg=json_data.getString("msg");
            //登入成功
            if(state)
            {
                //發送消息
                Message message= new Message();
                message.what=1;
                Bundle temp = new Bundle();
                temp.putString("msg",msg);
                message.setData(temp);
                handler.sendMessage(message);
 
            }
            //登入失敗
            else
            {
                Message message= new Message();
                message.what=2;
                Bundle temp = new Bundle();
                temp.putString("msg",msg);
                message.setData(temp);
                handler.sendMessage(message);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

} 數據庫

能夠看到界面啦 編程


   OK,adiOS json

相關文章
相關標籤/搜索