您的位置:首页 > 理论基础 > 计算机网络

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

2016-05-23 00:00 453 查看
一直在用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);

?>

```
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: