【问题标题】:Sending data via JSON from Android to PHP web service using HttpUrlConnection使用 HttpUrlConnection 通过 JSON 将数据从 Android 发送到 PHP Web 服务
【发布时间】:2016-02-22 00:27:55
【问题描述】:

我目前正在为一个小项目开发一个 Android 应用程序,该项目包括在 Android 平台上学习开发。我已经完成了所有应用程序,现在我需要将数据从应用程序发送到带有 MySQL 数据库的 PHP 服务器。我有一个 Web 服务,可以将通过 json 格式发送的数据插入数据库。我已经使用 Advanced Rest Client 测试了 Web 服务,并且成功地将数据插入到我的数据库中。现在我正在从我的 android 应用程序应用程序中进行测试,但它不起作用。我检查了连接状态,它是“OK”,但是当我检查数据库时,没有插入。

以下是我在 PHP 中的 Web 服务:

<?php  

$json = file_get_contents('php://input');
$obj = json_decode($json);
$con = mysql_connect('host','login','password') 
   or die('Cannot connect to the DB');
mysql_select_db('database_name',$con);
mysql_query("INSERT INTO `commercial` (firstName, surNameC, email, number, salonName, uuid)
VALUES ('".$obj->{'firstname'}."','".$obj->{'name'}."','".$obj->  {'email'}."','".$obj->{'phonenumber'}."','".$obj->{'fairreference'}."','".$obj-> {'commercialuuid'}."')");
mysql_close($con);

$posts = "INSERTION OK";
header('Content-type: application/json');
echo json_encode(array('posts'=>$posts)); 

?>

以及android端的发送过程:

    URL url;
    HttpURLConnection urlConnection;
    StringBuilder strBuilder;
    try {
        url = new URL(URL);
        urlConnection = (HttpURLConnection) url.openConnection();
        urlConnection.setRequestMethod("POST");
        urlConnection.setDoOutput(true);
        urlConnection.setUseCaches(false);
        urlConnection.setRequestProperty("Content-Type", "application/json");
        urlConnection.setReadTimeout(10000);
        urlConnection.setConnectTimeout(15000);
        urlConnection.connect();

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("commercialuuid", args[0]);
        jsonObject.put("name", args[1]);
        jsonObject.put("firstname", args[2]);
        jsonObject.put("phonenumber", args[3]);
        jsonObject.put("email", args[4]);
        jsonObject.put("fairreference", args[5]);

        Log.d("json", jsonObject.toString());
        Log.d("request", "starting");

        OutputStreamWriter writer = new   OutputStreamWriter(urlConnection.getOutputStream());
        writer.write(jsonObject.toString());
        writer.flush();

        Log.e("connection status",urlConnection.getResponseMessage());

        //get the response from the web service
        InputStream in = new BufferedInputStream(urlConnection.getInputStream());
        BufferedReader reader = new BufferedReader(new InputStreamReader(in));
        strBuilder = new StringBuilder();
        String line;
        while ((line = reader.readLine()) != null) {
            strBuilder.append(line);
        }
        writer.close();
        reader.close();
        urlConnection.disconnect();
        return null;

    } catch (Exception e) {
        e.printStackTrace();
    }

由于我搜索了几个经过验证的线程并基于我的工作,我真的不明白为什么它不起作用。 如果有人可以帮助我,我将不胜感激。

谢谢。

【问题讨论】:

  • 第一步,捕获mysql_query()的结果,看看这个:github.com/dmnugent80/ShareAppServerSide/blob/master/…
  • 感谢您的建议。我做到了,它非常有用。现在我有了一些进步,我插入但插入的对象中没有值。
  • 我已经打印了我在网络服务中收到的 json,它是空的。所以,问题在于我将 json 发送到 Web 服务的方式。还有另一种使用 outputstreamwriter 的方法吗?因为我检查了 Logcat 上的 json,它的创建和格式都很好。
  • 问题解决了!它完全来自我使用的免费服务器...buyethost...我已经在本地 wamp 服务器上对其进行了测试,并且可以正常工作!

标签: php android json web-services urlconnection


【解决方案1】:

-->更新: 正如 cmets 所说,这个答案现在已被弃用,您唯一的选择是使用 lib Retrofit,我现在使用它没有问题。寻找它,我建议使用 Retrofit2 而不是旧的。||

您可以使用 $post 发送您想要插入的数据

将其插入线程或异步任务中

List<NameValuePair> querypair=new ArrayList<NameValuePair>(1);
                        DefaultHttpClient httpClient = new DefaultHttpClient();;
                        querypair.add(new BasicNameValuePair("id", id));
                        querypair.add(new BasicNameValuePair("name", name));
                        querypair.add(new BasicNameValuePair("email", email));
                        HttpPost httpGetquery =new HttpPost("http://www.youradddres/insert.php");
                        httpGetquery.setEntity(new UrlEncodedFormEntity(querypair));
                        HttpResponse httpResponseGetQuery = httpClient.execute(httpGetquery);
                        httpEntityQueryGet = httpResponseGetQuery.getEntity();
                        Log.i("Entity",httpEntityQueryGet.toString());

也上传这个 php

<?php
$servername = "localhost";
$username = "user";
$password = "pass";
$dbname = "dbname";

$con=mysql_connect("localhost","$username","$password");
mysql_select_db("$dbname", $con);

$id=$_POST['id'];
$name=$_POST['name'];
$email=$_POST['email'];

mysql_query("INSERT INTO table(id, name, email)
VALUES ('$id', '$name', '$email')");

echo "New record created successfully";

?>

希望对你有帮助

【讨论】:

  • 您的 DBuser 也必须具有插入权限!
  • DefaultHttpClientBasicNameValuePair 在 api 22 中已弃用,并在 api 23 中删除。
  • 确实如此。而现在是JSON在平台之间操作数据的趋势
猜你喜欢
  • 1970-01-01
  • 2011-09-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-06-12
相关资源
最近更新 更多