我正在尝试通过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);
UPDATE 1
我现在添加了writer.flush(); (感谢安迪)现在,在sendung请求之后,我得到了这个异常:
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'];
}
感谢所有帮助!