okhttp通过post发送Json数据到php 更新数据库

一直在用HttpURLConnection连接PHP服务器,结果更新的数据库都是空值,一直找不到原因,也只能停手了,希望自己有一天能够解决吧~

改成用okHttp实现

1. 布局--简单地加个button,点击后提交json数据到PHP服务器,然后PHP更新数据库表

<?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. 权限 ----需要连接网络

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

3.okHttp.jar包的下载和okio.jar包的下载导入 

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

(2)如何导入,请自行搜索

4. android代码 ---(1)button添加监听器  (2)post 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);

    ?>

```

 

转载于:https://my.oschina.net/LaVictoria/blog/680082

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值