我必须为我的应用程序发出一些客户端-服务器请求。它可以工作,但我不能用PHP读取服务器中发布的参数。没有错误或异常。我尝试了很多不同的方法,但仍然不起作用。
private class NetworkProvider extends AsyncTask<NetworkingParams, String, String> {
@Override
protected String doInBackground(NetworkingParams... networkingParams) {
String url = networkingParams[0].getUrl();
String methodName = networkingParams[0].getMethodName();
JSONObject params = networkingParams[0].getParamJSON();
InputStream inputStream;
HttpPost httpPost;
HttpResponse httpResponse;
String result = "inputStream is null";
HttpClient httpClient = new DefaultHttpClient();
try {
params.put("method", methodName);
params.put("uNameDecoded", uNameDecoded);
params.put("uPassDecoded", uPassDecoded);
} catch (JSONException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
httpPost = createPostForJSONObject(params, url);
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Content-type", "application/json");
try {
httpResponse = httpClient.execute(httpPost);
inputStream = httpResponse.getEntity().getContent();
if (inputStream != null)
result = convertInputStreamToString(inputStream);
return result;
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
private HttpPost createPostForJSONObject(
JSONObject params, String url) {
HttpPost post = new HttpPost(url);
post.setEntity(createStringEntity(params));
return post;
}
private String convertInputStreamToString(InputStream inputStream) throws IOException{
BufferedReader bufferedReader = new BufferedReader( new InputStreamReader(inputStream));
String line = "";
String result = "";
while((line = bufferedReader.readLine()) != null)
result += line;
inputStream.close();
return result;
}
private HttpEntity createStringEntity(JSONObject params) {
StringEntity se = null;
try {
se = new StringEntity(params.toString());
} catch (UnsupportedEncodingException e) {
System.out.println("error creating entity");
}
return se;
}
}
问题是,数据是以JSON格式发送到服务器的,这在PHP的$POST中并不常见。我现在使用的不是"POST",而是"HTTP_RAW_POST_DATA"。工作非常完美。这就是我如何调试PHP后请求主体:
$entityBody = file_get_contents('php://input');
echo $entityBody;
PHP$POST的结构应该是这样的:"a=value"。不是"{"a":"value"}"。Java代码是正确的。