简体   繁体   English

从Java HTTPUrlConnection发送JSON,但是$ _POST变量在PHP中是否为空?

[英]Sending JSON from Java HTTPUrlConnection, but $_POST variable is empty in PHP?

I'm writing an Android app and I want to send some JSON data to a PHP server. 我正在编写一个Android应用程序,并且想将一些JSON数据发送到PHP服务器。 The POST request does go to the server but in my server.php script I check the $_POST variable and it is empty. POST请求确实到达了服务器,但是在我的server.php脚本中,我检查了$ _POST变量,该变量为空。 TCP/IP monitor is not in Eclipse ADT and wireshark doesn't show localhost request so I can't see what is actually being sent. TCP / IP监视器不在Eclipse ADT中,wireshark不显示localhost请求,因此我看不到实际发送的内容。 So does anyone have an idea what is being sent and how I can access it in PHP? 那么,有谁知道发送的内容以及如何在PHP中访问它? Or have I made a mistake in the code somewhere? 还是我在某处的代码中犯了一个错误?

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

try it. 试试吧。

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

you will get the output in str variable; 您将在str变量中获得输出;

I think is missing the flush Try os.flush(); 我认为缺少同花顺试试os.flush(); after os.write(..) 在os.write(..)之后

Don't use $_POST. 不要使用$ _POST。 Do something like this on user server 在用户服务器上执行类似的操作

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

    //you can do 
    echo $animals['dog'];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM