okhttp經過post發送Json數據到php 更新數據庫

一直在用HttpURLConnection鏈接PHP服務器,結果更新的數據庫都是空值,一直找不到緣由,也只能停手了,但願本身有一天可以解決吧~php

改爲用okHttp實現mysql

1. 佈局--簡單地加個button,點擊後提交json數據到PHP服務器,而後PHP更新數據庫表android

<?xml version="1.0" encoding="utf-8"?>
 <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
 xmlns:tools="http://schemas.android.com/tools" 
android:layout_width="match_parent" 
android:layout_height="match_parent" 
android:paddingBottom="@dimen/activity_vertical_margin" 
android:paddingLeft="@dimen/activity_horizontal_margin" 
android:paddingRight="@dimen/activity_horizontal_margin" 
android:paddingTop="@dimen/activity_vertical_margin" 
tools:context="com.pearl.subwayguider.MainActivity"> 
<Button android:layout_width="wrap_content" 
android:layout_height="wrap_content" 
android:text="login" 
android:id="@+id/login_btn" 
android:layout_alignParentTop="true" 
android:layout_alignParentLeft="true" 
android:layout_alignParentStart="true" 
android:layout_marginTop="53dp" />
 </RelativeLayout>

 

2. 權限 ----須要鏈接網絡git

<uses-permission android:name="android.permission.INTERNET"></uses-permission>

3.okHttp.jar包的下載和okio.jar包的下載導入 github

(1)http://square.github.io/okhttp/        此連接中有sql

(2)如何導入,請自行搜索數據庫

4. android代碼 ---(1)button添加監聽器  (2)post json數據方法json

(1)onCreate函數中服務器

loginbtn = (Button) findViewById(R.id.login_btn); 
loginbtn.setOnClickListener(new View.OnClickListener()
 { 
@Override public void onClick(View v) { 
new Thread(new Runnable() { 
@Override public void run() { 
postJson(); } }).start(); 
} });

(2)postJson方法網絡

public static final MediaType JSON = MediaType.parse("application/json; charset=utf-8"); 
private void postJson() { 
JSONObject user = new JSONObject();
 try { user.put("username","mary2"); 
user.put("password","sadbfdbds"); 
} catch (JSONException e) { 
e.printStackTrace(); } 
//申明給服務端傳遞一個json串 
//建立一個OkHttpClient對象 
OkHttpClient okHttpClient = new OkHttpClient(); 
//建立一個RequestBody(參數1:數據類型 參數2傳遞的json串)
 String json = user.toString();
 RequestBody requestBody = RequestBody.create(JSON,json); 
//建立一個請求對象 
Request request = new Request.Builder() .url("http://192.168.155.1/posttest.php") 
.post(requestBody) .build(); 
//發送請求獲取響應
try { Response response=okHttpClient.newCall(request).execute(); 
//判斷請求是否成功
 if(response.isSuccessful()){
 //打印服務端返回結果 Log.i("Success tag",response.body().string()); 
} } catch (IOException e) { e.printStackTrace(); } }

5. php代碼,放在www目錄下 文件名爲posttest.php

``` php

    <?php  
    //$json=$_POST ['json'];
    error_reporting(E_ALL ^ E_DEPRECATED);
    //$json = '{"username": "dsvcjf","password":"ddfshfd"}';
    //echo $json;
    echo ($json = file_get_contents('php://input'));
    $obj = json_decode($json);


    //Save
    $con = mysql_connect('localhost','root','123456') or die('Cannot connect     to the DB');
    mysql_select_db('test',$con);

      /* grab the posts from the db */
      //$query = "SELECT post_title, guid FROM wp_posts WHERE post_author     = $user_id AND post_status = 'publish' ORDER BY ID DESC LIMIT     $number_of_posts";
      $u=$obj->{'username'};
      $p=$obj->{'password'}; 

    mysql_query("INSERT INTO `test` (username, password) VALUES     ('$u','$p')");

    mysql_close($con);

    ?>

```

相關文章
相關標籤/搜索