我正在尝试使用 Android Studio 中的 POST 请求从我的 PHP 脚本接收一个简单的字符串。 例如,如果我写 echo "Hello";我可以在我的应用程序中收到此消息,但似乎只要我发送 POST 请求,我的网络服务器就无法真正收到该消息。
以下是我在 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
}
}
}
正如你所看到的,我正在使用这个:
JsonObject postData = new JsonObject();
postData.addProperty("a", "1");
生成我的 POST 请求。
postData 字符串为:{"a":"1"}
这是我的 PHP 脚本:
$post = file_get_contents("php://input");
$data = json_decode($post, true);
print_r($data);
更新1
我现在添加了 writer.flush(); (感谢安迪) 现在我在发送请求后收到此异常:
java.io.IOException: Invalid response from server: 500
所以我的 PHP 脚本有问题。
有什么建议吗?
最佳答案
我现在发现问题了。 问题并不像我预期的那样出现在服务器端。
我在我的代码中记录了 POST 请求的一些信息,在那里我发现了这个:
Log.i("LOG", urlConnection.getOutputStream().toString());
给了我这个:
buffer(com.android.okhttp.internal.http.HttpConnection$ChunkedSink@843d1c8).outputStream()
所以我评论了这一行:
urlConnection.setChunkedStreamingMode(0);
而且效果很好。我获得了所需的所有数据。
我还将我的 PHP 脚本更新为:
$post = file_get_contents("php://input");
if (!empty($post))
{
$data = json_decode($post, true);
$a = $data['a'];
}
感谢您的帮助!
关于java - PHP 未使用 AsyncTask 接收来自 POST 请求的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60029128/