1. 程式人生 > >Android客戶端與伺服器端簡單互動

Android客戶端與伺服器端簡單互動

客戶端程式碼:

/**
     * 功能:通過Get向伺服器請求Json資料
     * 說明:1.字串(一般用{}表示)與陣列(一般用[]表示)的解析方式是不一樣的,具體如下:
     *        (1)如果返回的是Json字串,則使用JSONObject jsonObject=new JSONObject(jsonString);
     *        (2)如果返回的是Json陣列,則使用JSONArray jsonArray =new JSONArray(jsonString);
     */
    public void doHttpGetJSON(final String url){
        // 新建一個執行緒
        new Thread() {
            @Override
            public void run() {
                HttpClient httpClient = new DefaultHttpClient();
                //指定伺服器端URL
                HttpGet get = new HttpGet(url);
                try {
                    HttpResponse rsp = httpClient.execute(get);
                    // 獲取響應的實體
                    HttpEntity httpEntity = rsp.getEntity();
                    // 將響應的實體轉換為Json字串
                    String jsonString = EntityUtils.toString(httpEntity);
                    // 將Json字串轉換為Json物件

                    /**
                     * 返回的是Json字串時,用JSONObject物件
                     */
//                    JSONObject jsonObject =new JSONObject(jsonString);
//                    String username = jsonObject.getString("username");
//                    String password = jsonObject.getString("password");
//                    Log.e("Json", username);
//                    Log.e("Json", password);

                    /**
                     * 返回的是Json陣列時,用JSONArray陣列
                     */
                    JSONArray jsonArray =new JSONArray(jsonString);
                    for (int i = 0; i < jsonArray.length(); i++) {
                        JSONObject jsonObject = (JSONObject) jsonArray.get(i);
                        // 取出name
                        String username = jsonObject.getString("username");
                        String password = jsonObject.getString("password");
                        // 向主(UI)執行緒傳送訊息,更新UI
                        Message msg = new Message();
                        msg.what = 0x123;
                        Bundle bundle = new Bundle();
                        bundle.putString("username",username);
                        bundle.putString("password",password);
                        msg.setData(bundle);
                        MainActivity.this.mHandler.sendMessage(msg);
//                        // 將下載的資料插入本地資料庫
//                        ContentValues values = new ContentValues();
//                        values.put("username", username);
//                        values.put("password", password);
//                        db.insert("person", null, values); // 引數依次是:表名,強行插入null值得資料列的列名,一行記錄的資料
                        //Log.e("username", username);
                        //Log.e("password", password);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                } catch(JSONException e) {
                    e.printStackTrace();
                }
            }
        }.start();
    }

/**
     * 功能:通過Post向伺服器提交Json資料
     * 說明:1.HttpClient不能用DefaultHttpClient替換,會出現問題
     */
    public void doHttpPostJSON(final String url){
        // 新建一個執行緒
        new Thread() {
            @Override
            public void run(){
                /**
                 * 提交的是Json字串時,用JSONObject物件
                  */
//                JSONObject jsonObj = new JSONObject();
//                try {
//                    jsonObj.put("username", edt_username.getText().toString())
//                            .put("password", edt_password.getText().toString());
//                } catch (JSONException e) {
//                    e.printStackTrace();
//                }
//                String jsonString = jsonObj.toString();
                /**
                 * 提交的是Json陣列時,用JSONArray陣列
                  */
                JSONArray jsonArray = new JSONArray();
                try {
                    jsonArray.put(new JSONObject().put("username", edt_username.getText().toString())
                                                  .put("password", edt_password.getText().toString()));
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                String jsonString = jsonArray.toString();

                // 指定Post引數
                List<NameValuePair> nameValuePairs = new ArrayList<>();
                nameValuePairs.add(new BasicNameValuePair("data", jsonString));

                try {
                    //發出HTTP請求
                    HttpClient httpClient = new DefaultHttpClient();
                    HttpPost httpPost = new HttpPost(url);
                    httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
                    System.out.println("executing request " + httpPost.getURI());

                    HttpResponse httpResponse = httpClient.execute(httpPost);
                    try {
                        HttpEntity httpEntity = httpResponse.getEntity();
                        if (httpEntity != null) {
                            System.out.println("--------------------------------------");
                            System.out.println("Response content: " + EntityUtils.toString(httpEntity, "UTF-8"));
                            System.out.println("--------------------------------------");
                        }
                    }
                    finally {
                        System.out.println("--------------------------------------");
                    }
                }
                catch (UnsupportedEncodingException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                catch (ClientProtocolException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }.start();
    }

伺服器端程式碼:
// servertoclient.php
<?php 
	$arr=array(
		array(
		 'username'=>'a',
		 'password'=>'123',
		 ),
		array(
		 'username'=>'b',
		 'password'=>'2',
		 ),
		array(
		 'username'=>'c',
		 'password'=>'3',
		 )
		);
	echo json_encode($arr);
?> 

// clienttoserver 
<?php
	$arr = json_decode($_POST['data']);
        $username = $arr[0]->{'username'};
        $password = $arr[0]->{'password'};

        if(empty($username) or empty($password)){
               die("You have to fill all the fields!");
        }
        $conn = mysql_connect('localhost','root','');
        if(!$conn){
                die("connection failed:".mysql_error());  
		}

        mysql_select_db('mysql',$conn);

        $query = "insert into e_bike (username, password) values('$username','$password')";
        $result = mysql_query($query,$conn);
        if(!$result){
                die("mysql error:".mysql_error());
        }
	
        echo "add information to database sucessfullly!";
?>