使用POST方法和HttpURLConnection将JSON对象从Android发送到PHP服务器

时间:2015-08-20 09:36:17

标签: php android json

我正在尝试在我的Android应用和本地网络上的WampServer之间建立通信。

当我想从服务器读取数据时,我已经取得了成功,但是当我尝试将数据发送到服务器时遇到了问题。

我正在使用服务来建立沟通:

public class SynchronisationService extends Service {
@Override
public IBinder onBind(Intent intent) {
    return null;
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    super.onStartCommand(intent, flags, startId);

    new Thread(new Runnable() {
        @Override
        public void run() {
            try {
                URL url = new URL("http://192.168.37.23/happiness_barometer/php_input.php");
                HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                connection.setDoOutput(true);
                connection.setDoInput(false);
                connection.setRequestMethod("POST");
                connection.connect();
                OutputStream outputStream = connection.getOutputStream();
                OutputStreamWriter writer = new OutputStreamWriter(outputStream);
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("rate", 1);
                writer.write(URLEncoder.encode(jsonObject.toString(), "UTF-8"));
                writer.flush();
                writer.close();

            } catch (Exception e) {
                Log.v("EXCEPTION", e.getMessage());
            }
        }
    }).start();


    stopSelf();

    return flags;
}

}

我的php文件:

 <?php 

    try 
    {
        $bdd = new PDO('mysql:host=localhost;dbname=happiness_barometer;charset=utf8', 'utilisateur', '');
    } catch (Exception $e) 
    {
        die('Erreur : '.$e->getMessage());
    }

    $sql = $bdd->prepare(
    'INSERT INTO rates (rate, comment, category, day, month, year, hour, minute, day_of_week, week, rate_number) 
    VALUES (:rate, :comment, :category, :day, :month, :year, :hour, :minute, :day_of_week, :week, :rate_number)');
    if (!empty($_POST['rate'])) {
        $sql->execute(array(
            'rate' => $_POST['rate'],
            'comment' => '',
            'category' => 'pro',
            'day' => 19,
            'month' => 8,
            'year' => 2015,
            'hour' => 18,
            'minute' => 3,
            'day_of_week' =>3,
            'week' => 33,
            'rate_number' => 2));
    }
?>

当我运行我的应用程序时,我的数据库中没有添加任何内容。 我认为$_POST['rate']中没有任何内容。

请告诉我我的代码有什么问题?

1 个答案:

答案 0 :(得分:1)

检查此代码:

public class UniversalNetworkConnection {

    public static String postJSONObject(String myurl, JSONObject parameters) {
        HttpURLConnection conn = null;
        try {
            StringBuffer response = null;
            URL url = new URL(myurl);
            conn = (HttpURLConnection) url.openConnection();
            conn.setReadTimeout(10000);
            conn.setConnectTimeout(15000);
            conn.setRequestProperty("Content-Type", "application/json");
            conn.setDoOutput(true);
            conn.setRequestMethod("POST");
            OutputStream out = new BufferedOutputStream(conn.getOutputStream());
            BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(out, "UTF-8"));
            writer.write(parameters.toString());
            writer.close();
            out.close();
            int responseCode = conn.getResponseCode();
            System.out.println("responseCode" + responseCode);
            switch (responseCode) {
                case 200:
                    BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
                    String inputLine;
                    response = new StringBuffer();
                    while ((inputLine = in.readLine()) != null) {
                        response.append(inputLine);
                    }
                    in.close();
                    return response.toString();
            }
        } catch (IOException ex) {
            ex.printStackTrace();
        } finally {
            if (conn != null) {
                try {
                    conn.disconnect();
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            }
        }
        return null;
    }

}
PHP端的

<?php
    $json = file_get_contents('php://input');
    $obj = json_decode($json);
    print_r($obj);
    print_r("this is a test");
?>