android + php 後臺開發

android+php 安卓與服務器的數據交互

在咱們進行android開發的時候,避免不了的要進行登陸註冊,我的信息獲取,數據交互等等這一系列的操做。這樣就須要進行android端與服務器端進行數據的交互。但如何讓他們進行數據的一個交互,我在這裏也踩了很多坑,不過最後也算是交互成功了,下面我把個人方法寫一下,不敢說是最好的,最起碼是能夠使用的,也請你們多多指教。

在經過上網查資料的時候,我發現android想要往服務器端傳遞數據的話能夠使用的方法很是的多。HttpClient ,HttpResponse ,OkHttpClient ,HttpURLConnection等等好多的方法,可是我發現裏面有好多的方法所使用的包都是最原始的類庫中不存在的(也多是我沒有找到合適的使用方法)。試驗到最後,我決定使用HttpURLConnection這個類來實現,由於感受這個不須要另外再從網上下載其餘的類庫,比較簡單方便,直接能夠使用。服務器端的話我是採用我比較熟悉的Apache+php來進行搭建的。php

android與PHP的交互是經過http網絡編程實現的。須要遵照http協議。經過http://www......域名來實現訪問。利用PHP文件做爲接口進行數據庫的遠程操做。而android與PHP之間的數值傳遞是經過json數據類型。下面會有具體的java與PHP對於json數據類型的處理。下面我來展現一下。java

第一步:首先須要先定義能訪問到你服務器的url地址,能夠直接填寫IP地址,也能夠填寫能訪問到服務器的域名信息。例如你能夠填寫:http://www.myServer.com/test.php 或者 http://111.111.111.11/test.php,用一個URl類轉換一下android

//創建網絡鏈接
String url_str= "http://111.111.111.11/test.php";
URL url=new URL(url_str);
HttpURLConnection http = (HttpURLConnection)url.openConnection();

第二步:設置鏈接的參數設置網絡鏈接的一些參數,利用post進行數據的傳輸,跟網頁的post傳遞相似。數據庫

//設置是否向httpUrlConnection 輸出,由於設置的是post請求,參數放在http正文中,所以須要設爲true,默認狀況下是false;
http.setDoOutput(true);
//設置是否從httpUrlConnection讀入,默認狀況下是true
http.setDoInput(true);
//設置請求方式
http.setRequestMethod("POST");
//設置 post請求不能使用緩存
http.setUseCaches(false);
//這個設置比較重要,設置http請求的數據類型以及編碼格式,由於這裏使用json來傳遞數據,因此這一設置是json.
http.setRequestProperty("Content-type", "application/json;charset=utf-8");
//若是想要日後臺傳遞圖片的話,這裏的設置有些不一樣,固然還會有其餘的不一樣,這裏先不詳解了。
//http.setRequestProperty("Connection", "Keep-Alive");
//http.setRequestProperty("Charset", "UTF-8");
//http.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + "****");
//創建鏈接
http.connect();

//還會有一些其餘參數,這個參數的設置能夠根據本身的實際狀況進行選擇

第三步:獲取輸入流,寫入要傳遞的數據。編程

OutputStream out=http.getOutputStream();
 //建立json對象並添加數據。
 data = new JSONObject();
 data.put("name","Myname");
 data.put("password","MyPassword");
 
 //post請求
out.write(data.toString().getBytes());
out.flush();
out.close();

第四步:獲取服務器端返回的數據。json

//獲取網頁返回數據
//獲取輸入流
BufferedReader bufferedReader =new BufferedReader(new InputStreamReader(http.getInputStream()));
String line ="";
StringBuilder builder = new StringBuilder(); //創建輸入緩衝區
while(null != (line=bufferedReader.readLine())){ //結束會讀入一個null值
            line = new String(line.getBytes(),"utf-8");
            builder.append(line); //寫入緩衝區
     }
String result = builder.toString(); //返回結果
bufferedReader.close();
http.disconnect();

//若是鏈接成功result裏面記錄的是後臺返回的數據。

第五步:就是進行數據的解析,獲取後臺返回的數據。數組

//把獲取的字符串經過轉換成json形式的數據類型
    JSONObject jsonObject=new JSONObject(result);
    //獲取裏面的數據
    returnResult=jsonObject.getInt("status");
    if(returnResult !=0){ 
    //若是返回的json裏還有數組,須要用jsonArray進行獲取,而後再從獲取的數據裏逐個獲取json數據。
    user_account=jsonObject.getString("telephone");
    address=jsonObject.getString("address");
    username=jsonObject.getString("username");
    sex=jsonObject.getString("sex");

PHP服務器端

PHP進行接收文件的時候不用再用$_POST或者$_REQUEST進行數據的接收。由於android傳遞過來的不是表單的數據,而是一個數據流,因此須要進行輸入數據流的接收。緩存

$data=json_decode(file_get_contents("php://input"),true);
$data[···] = ····;

.....


return json_encode(['status'=>1,"message"=>"成功接收數據"]);

以我作的登陸實例來進行所有代碼的展現。

android端
private int login(String telephone,String password) throws IOException, JSONException {
        int returnResult=0;

        //創建網絡鏈接
        String urlstr="你的服務器url地址";
        URL url=new URL(urlstr);
        HttpURLConnection http=(HttpURLConnection)url.openConnection();

        http.setDoOutput(true);
        http.setDoInput(true);
        http.setRequestMethod("POST");
        http.setUseCaches(false);
        http.setRequestProperty("Content-type", "application/json;charset=utf-8");
        http.connect();

        //獲取輸入流,想服務器寫入數據
        OutputStream out=http.getOutputStream();
        //post請求
        JSONObject data=new JSONObject();
        data.put("telephone",telephone);
        data.put("password",password);
        out.write(data.toString().getBytes());
        out.flush();
        out.close();

        //讀取網頁返回的數據
        BufferedReader bufferedReader=new BufferedReader(new InputStreamReader(http.getInputStream()));//獲取輸入流
        String line="";
        StringBuilder builder=new StringBuilder();//創建輸入緩衝區
        while(null !=(line=bufferedReader.readLine())){ //結束會讀入一個null值
            line=new String(line.getBytes(),"utf-8");
            builder.append(line); //寫緩衝區
        }
        String result=builder.toString(); //返回結果
        bufferedReader.close();
        http.disconnect();

        try{
            //獲取服務器返回的Json數據
            JSONObject jsonObject=new JSONObject(result);
            returnResult=jsonObject.getInt("status");
            if(returnResult !=0){
                user_account=jsonObject.getString("telephone");
                address=jsonObject.getString("address");
                username=jsonObject.getString("username");
                sex=jsonObject.getString("sex");
                if(username == null){
                    username ="未輸入暱稱";
                }
            }

        } catch (JSONException e) {
            Log.e("log_tag", "the Error parsing data "+e.toString());
        }
        return returnResult;

    }

php端

function Login(){
        $value=array();
        $data=array();

        //php文件接收輸入端傳遞的數據流
        $value=json_decode(file_get_contents("php://input"),true);
        //查找數據庫,判斷是否存在該用戶
        $login=Db::name("Db_name")->where('telephone',$value['telephone'])->find();
        if(!$login){
            return ['status'=>0];
        }else{
            $password=md5($value['password']);
            if($password == $login['password']){
                return ['status'=>$login['id'],"telephone"=>$login['telephone'],'username'=>$login["username"],"address"=>$login["address"],"sex"=>$login["sex"]];
            }else{
                return ['status'=>0];
            }
        }

    }

初次搭建android的後臺,有什麼不妥的地方還請你們不吝賜教。服務器

相關文章
相關標籤/搜索