简体   繁体   English

PHP 没有从带有 AsyncTask 的 POST 请求接收数据

[英]PHP is not receieving data from a POST request with AsyncTask

I am trying to receieve a simple string from my PHP script by using a POST request in Android Studio.我试图通过在 Android Studio 中使用 POST 请求从我的 PHP 脚本中接收一个简单的字符串。 If I write for example echo "Hello";如果我写例如 echo "Hello"; I can receive this message in my app, but it seems like as soon as I send a POST request my webserver doesen't really get the message.我可以在我的应用程序中收到此消息,但似乎一旦我发送 POST 请求,我的网络服务器就没有真正收到消息。

Here is how I do the POST request in my AsyncTask :这是我在AsyncTask 中执行 POST 请求的方法:

class HTTPReqTask extends AsyncTask<String, Void, String>
{
    Activity activity;
    OnDataSendToActivity dataSendToActivity;
    Context context;

    public HTTPReqTask(Context context)
    {
        this.context = context;
        dataSendToActivity = (OnDataSendToActivity) ((Activity) context);
    }

    @Override
    public String doInBackground(String... params)
    {
        HttpURLConnection urlConnection = null;
        String param1 = params[0];
        String line = "";
        String result = "";

        try
        {
            JsonObject postData = new JsonObject();
            postData.addProperty("a", "1");

            URL url = new URL(param1);
            urlConnection = (HttpURLConnection) url.openConnection();
            urlConnection.setRequestProperty("Content-Type", "application/json");
            urlConnection.setRequestMethod("POST");
            urlConnection.setDoOutput(true);
            urlConnection.setDoInput(true);
            urlConnection.setChunkedStreamingMode(0);

            OutputStream out = new BufferedOutputStream(urlConnection.getOutputStream());
            BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(out,"UTF-8"));
            writer.write(postData.toString());

            int code = urlConnection.getResponseCode();
            if (code !=  HttpURLConnection.HTTP_OK) {
                throw new IOException("Invalid response from server: " + code);
            }

            BufferedReader rd = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));

            while ((line = rd.readLine()) != null)
            {
                result += line;
            }
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        finally
        {
            if (urlConnection != null)
            {
                urlConnection.disconnect();
            }
        }

        return result;
    }

    @Override
    protected void onPostExecute(String s)
    {
        try
        {
            if(dataSendToActivity != null)
            {
                Log.i("Data", s);
                dataSendToActivity.sendData(s);
            }
        }
        catch(Exception e)
        {
            // Nichts
        }

    }
}

As you can see I am using this:正如你所看到的,我正在使用这个:

JsonObject postData = new JsonObject();
postData.addProperty("a", "1");

to generate my POST request.生成我的 POST 请求。

The postData string is: {"a":"1"} postData字符串是:{"a":"1"}

This is my PHP script:这是我的 PHP 脚本:

$post = file_get_contents("php://input");
$data = json_decode($post, true);

print_r($data);

UPDATE 1更新 1

I added now writer.flush();我现在添加了 writer.flush(); (Thanks to Andy) Now I'm getting this exception after sendung the request: (感谢安迪)现在我在发送请求后收到此异常:

java.io.IOException: Invalid response from server: 500

So something with my PHP script is wrong.所以我的 PHP 脚本有问题。

Any suggestions?有什么建议?

I found now the problem.我现在发现了问题。 The problem was not serversided as I expected it.问题并不像我预期的那样是服务器端的。

I was logging in my code some informations for the POST request and there I found this:我在我的代码中登录了 POST 请求的一些信息,在那里我发现了这个:

Log.i("LOG", urlConnection.getOutputStream().toString());

gave me this:给了我这个:

buffer(com.android.okhttp.internal.http.HttpConnection$ChunkedSink@843d1c8).outputStream()

So I commented this line out:所以我注释掉了这一行:

urlConnection.setChunkedStreamingMode(0);

and it works fine.它工作正常。 I get all my data I need.我得到了我需要的所有数据。

I also updated my PHP script to this:我还将我的 PHP 脚本更新为:

$post = file_get_contents("php://input");

if (!empty($post))
{
    $data = json_decode($post, true);
    $a = $data['a'];
}

Thanks for all the help!感谢所有的帮助!

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

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