【问题标题】:Sending JSON from Java HTTPUrlConnection, but $_POST variable is empty in PHP?从 Java HTTPUrlConnection 发送 JSON,但 PHP 中的 $_POST 变量为空?
【发布时间】:2012-12-16 11:21:15
【问题描述】:

我正在编写一个 Android 应用程序,我想将一些 JSON 数据发送到 PHP 服务器。 POST 请求确实会发送到服务器,但在我的 server.php 脚本中,我检查了 $_POST 变量,它是空的。 TCP/IP 监视器不在 Eclipse ADT 中,wireshark 不显示 localhost 请求,所以我看不到实际发送的内容。那么有没有人知道正在发送什么以及如何在 PHP 中访问它?还是我在某处的代码中犯了错误?

   JSONObject json = new JSONObject();

    try {
        json.put("dog", "cat");
    } catch (JSONException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }

    HttpURLConnection urlConnection = null;
    try {
        URL url = new URL("http://10.0.2.2/server.php");
        urlConnection = (HttpURLConnection)url.openConnection();
        urlConnection.setRequestProperty("Content-Type", "application/json");
        urlConnection.setRequestProperty("Accept", "application/json");
        urlConnection.setRequestMethod("POST");         
        urlConnection.setDoOutput(true);
        OutputStreamWriter os = new OutputStreamWriter(urlConnection.getOutputStream(), "UTF-8");
        os.write(json.toString());
        os.close();
    }

【问题讨论】:

  • 你从服务器得到什么响应?
  • 检查 $_REQUEST 看看你得到了什么。
  • @t0s 它正在将 server.php 页面的 HTML 发回给我。
  • 代码看起来不错...从charlesproxy.com/download 获取Charles 监控软件,并将其代理设置为指向您的Web 服务器。这应该允许您捕获 localhost 请求并查看其内容。
  • 有人删除了他们对我的回复......他们的回复是正确的,一旦我设置了 urlConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded") 数据是出现在服务器上。

标签: java php android json


【解决方案1】:

试试看。

JSONObject json = new JSONObject();

    try {
        json.put("dog", "cat");
    } catch (JSONException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }

HttpClient localDefaultHttpClient=new DefaultHttpClient();
        HttpPost lotlisting = new HttpPost("http://10.0.2.2/server.php");
        ArrayList localArrayList = new ArrayList();
        localArrayList.add(new BasicNameValuePair("json",json.toString()));
        try {
            lotlisting.setEntity(new UrlEncodedFormEntity(localArrayList));
            String str = EntityUtils.toString(localDefaultHttpClient.execute(lotlisting).getEntity());

        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

您将在 str 变量中获得输出;

【讨论】:

    【解决方案2】:

    我认为缺少冲洗 试试 os.flush();在 os.write(..) 之后

    【讨论】:

      【解决方案3】:

      不要使用 $_POST。在用户服务器上做这样的事情

          $json = file_get_contents('php://input');
          $animals= json_decode($json,true);
      
          //you can do 
          echo $animals['dog'];
      

      【讨论】:

        猜你喜欢
        • 2018-05-09
        • 1970-01-01
        • 2017-11-27
        • 2020-02-21
        • 2011-04-14
        • 1970-01-01
        • 1970-01-01
        • 2017-03-18
        • 1970-01-01
        相关资源
        最近更新 更多