使用HttpURLConnection将json对象发送到本地php服务器

时间:2016-02-22 14:03:59

标签: php android

我试图将android中的json对象发送到本地php服务器(XAMPP)。 这是我的PHP脚本,它收到了该对象。

<?php

  $response = array();

  if (isset(($_POST['PNR_NO'])&&($_POST['Status'])&&($_POST['update_time']))){

      $PNR_NO = $_POST['PNR_NO'];
      $Status = $_POST['Status'];
      $update_time = $_POST['update_time'];

      // include db connect class
      require_once __DIR__ . '/db_connect.php';

      // connecting to db
      $db = new DB_CONNECT();

      // mysql inserting a new row
      $result = mysql_query("INSERT INTO pnr_database(PNR_NO, Status,update_time) VALUES('$PNR_NO', '$Status', '$update_time')");

      // check if row inserted or not
      if ($result) {
          // successfully inserted into database
          $response["success"] = 1;
          $response["message"] = "Product successfully created.";

          // echoing JSON response
          echo json_encode($response);
      }
      else {
          // failed to insert row
          $response["success"] = 0;
          $response["message"] = "Oops! An error occurred.";

          // echoing JSON response
          echo json_encode($response);
      }
  }
  else {
      $response["success"] = 0;
      $response["message"] = "Required field(s) is missing";

      echo json_encode($response);
   }?>

我正在使用的java代码是:

@Override
    protected Void doInBackground(String... urls) {
        OutputStream os;
        HttpURLConnection conn = null;
        try {
            //constants
            String pnr = "1234";
            String stat = "WC12";
            String updTime = "13:20";
            Log.i("aaaaa", "Started");
            URL url = new URL(urls[0]);
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("PNR_NO",pnr );
            jsonObject.put("Status", stat);
            jsonObject.put("update_time", updTime);
            String message = jsonObject.toString();
            System.out.println(message);
            conn = (HttpURLConnection) url.openConnection();
            conn.setReadTimeout(10000 /*milliseconds*/);
            conn.setConnectTimeout(15000 /* milliseconds */);
            conn.setRequestMethod("POST");
            conn.setDoInput(true);
            conn.setDoOutput(true);
            conn.setFixedLengthStreamingMode(message.getBytes().length);


            conn.setRequestProperty("Content-Type", "application/json;charset=utf-8");
            conn.setRequestProperty("X-Requested-With", "XMLHttpRequest");

            //open
            conn.connect();

            //setup send
            os = new BufferedOutputStream(conn.getOutputStream());
            os.write(message.getBytes());
            Log.i("aaaaa","ended");
            //clean up
            os.flush();
        }
        catch (IOException e) {
            e.printStackTrace();
        }
        catch (JSONException ex) {
            ex.printStackTrace();
        }
        finally {

            //clean up

        /*try {
            os.close();
            is.close();
        }
        catch (IOException e) {
            e.printStackTrace();
        }
        */
            conn.disconnect();
        }
        return null;
    }

基本上我想将数据发送到我的php服务器,在那里我创建了一个数据库,其中有一个名为pnr_database的表,发送的数据应该存储在该表中。我不希望服务器有任何响应。

但是我的代码无效......

我从一个html表单测试了我的PHP脚本,我将数据发送到服务器...在这种情况下,PHP脚本工作正常,数据存储在数据库中但是我无法在android中使其​​工作。 / p>

1 个答案:

答案 0 :(得分:0)

这可能是一个迟到的答案。但是你在php中收到的JSON是经过编码的,因此你需要在if子句中对它进行解码:

$decoded = json_decode($_POST, true); //this will return an array
$PNR_NO = $decoded['PNR_NO'];
$Status = $decoded['Status'];
$update_time = $decoded['update_time'];

您可以在此处输入表格的列。