我想将一些表单详细信息从我的android应用发送到后端php脚本中。我为此使用了Android Volley库。它发送json对象(从android端报告没有错误),但是我的php脚本没有捕获任何json对象。
Android代码
StringRequest postRequest = new StringRequest(Request.Method.POST, posturl,
new Response.Listener<String>()
{
@Override
public void onResponse(String response) {
// response
Log.d("Response", response);
}
},
new Response.ErrorListener()
{
@Override
public void onErrorResponse(VolleyError error) {
// error
Log.d("Error.Response", error.toString());
}
}
) {
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("Content-Type", "application/json");
return params;
}
@Override
protected Map<String, String> getParams()
{
Map<String, String> params = new HashMap<String, String>();
params.put("name", "John");
params.put("birthdate", "1988 03 29");
return params;
}
};
queue.add(postRequest);
PHP代码
if(strcasecmp($_SERVER['REQUEST_METHOD'], 'POST') != 0){
throw new Exception('Request method must be POST!');
}
$contentType = isset($_SERVER["CONTENT_TYPE"]) ? trim($_SERVER["CONTENT_TYPE"]) : '';
if(strcasecmp($contentType, 'application/json') != 0){
throw new Exception('Content type must be: application/json');
}
$decoded = trim(file_get_contents("php://input"));
$decoded1 = json_decode($decoded, true);
printf("decoded data %s",$decoded1);
if(!is_array($decoded1)){
throw new Exception('Received content contained invalid JSON!');
}