Android客户端与服务器端简单交互

来源:互联网 发布:阿里云虚拟主机打不开 编辑:程序博客网 时间:2024/05/01 16:16

客户端代码:

/**     * 功能:通过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!";?>



0 0
原创粉丝点击