0

我正在编写一个 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();
    }
4

3 回答 3

5

尝试一下。

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 变量中获得输出;

于 2013-01-02T09:43:40.333 回答
1

我认为缺少刷新尝试 os.flush(); 在 os.write(..) 之后

于 2013-01-02T02:37:09.740 回答
1

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

    $json = file_get_contents('php://input');
    $animals= json_decode($json,true);

    //you can do 
    echo $animals['dog'];
于 2016-01-09T18:58:06.217 回答