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 に答える