使用HttpUrlConnection通过JSON从Android向PHP Web服务发送数据

时间:2015-11-19 17:57:34

标签: php android json web-services urlconnection

我目前正在为一个小项目开发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();
    }

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

感谢。

1 个答案:

答案 0 :(得分:2)

<强> - &GT;更新: 正如评论所说,这个答案现在已被弃用,您唯一的选择是使用lib Retrofit,我现在可以毫无问题地使用它。寻找它,我建议使用Retrofit2而不是旧版。||

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

将其插入线程或异步任务

var/www

还上传此php

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());

希望有所帮助