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架構。詳細的伺服器搭建就不說了。給出主要響應代碼: - <?php
- namespace Home\Controller;
- use Think\Controller;
- class AndroidController 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'=>'賬号或密碼錯誤');
-
-
-
- }
- }
複制代碼 記得添加網絡權限 <uses-permission android:name="android.permission.INTERNET"></uses-permission> Android的網絡請求主要使用java.net包中的HttpURLConnection類,伺服器與Android用戶端資料互動格式為json 1.利用POST請求方式來實作人員登入。 - 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/Android";
- 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:
-
-
-
- }
- }
- };
- start.setOnClickListener(new View.OnClickListener() {
-
- 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("POST");//以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(new OutputStreamWriter(conn.getOutputStream()));
- bw.write(params);
- bw.close();
- //接收伺服器響應
- if (conn.getResponseCode() == 200) {
- InputStream is = conn.getInputStream();//得到網絡傳回的輸入流
- BufferedReader buf=new BufferedReader(new InputStreamReader(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.what=2;
-
-
-
-
-
- } catch (JSONException e) {
- e.printStackTrace();
- }
-
-
2.利用GET請求方式來實作人員登入 -
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- //請求位址--
- String url="http://10.0.2.2:8080/think/index.php/Home/Android?"+ "username=" + URLEncoder.encode(username.getText().toString(), "UTF-8")
- + "&password=" + URLEncoder.encode(password.getText().toString(), "UTF-8");
-
-
-
-
-
-
- conn.setRequestMethod("GET");//以get方式發起請求
- //允許輸入流
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
運作結果: |