使用 HttpUrlConnection 在 Android 设备和 PHP Web 服务之间通过 JSON 发送数据

3
我正在开发一款Android应用程序,这是一个学习在Android平台上开发的小项目。我已经完成了所有应用程序,现在需要通过PHP和MySQL数据库将数据从应用程序发送到服务器。我有一个Web服务,可以通过json格式的数据将其插入到数据库中。我已经使用高级REST客户端测试了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()的结果,请查看此链接:https://github.com/dmnugent80/ShareAppServerSide/blob/master/databaseInsert.php - Daniel Nugent
谢谢你的建议。我已经做了,非常有用。现在我有一些进展,我插入了但插入的对象中没有值。 - f.chd
我已经打印出了我从Web服务接收到的JSON,但它是空的。所以问题在于我发送JSON到Web服务的方式。除了使用OutputStreamWriter之外,是否还有其他方法?因为我在Logcat上检查了JSON,它被正确创建和格式化了。 - f.chd
问题解决了!完全是因为我使用的免费服务器...buyethost...我已经在本地wamp服务器上测试过了,它可以工作! - f.chd
1个回答

2

-->更新:根据评论,此答案已过时,您唯一的选择是使用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";

?>

希望这有所帮助。

同时,您的DB用户必须具有插入权限! - Carlos Montiel
DefaultHttpClientBasicNameValuePair在api 22中已被弃用,并在api 23中移除。 - Daniel Nugent
的确是这样。现在JSON成为了在平台之间操作数据的趋势。 - f.chd

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接