在我的 PHP API 中使用 Volley 时遇到了同样的问题。事实证明,一个JSONObject
参数作为 JSON 发送。因此,PHP $_POST 不会识别它,因为它不是以下格式:param1=value1¶m2=value
要亲自查看,请尝试:print file_get_contents("php://input");
我的解决方案是创建一个扩展Request<JSONObject>
而不是使用的解决方法类JsonObjectRequest
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.AuthFailureError;
import com.android.volley.NetworkResponse;
import com.android.volley.ParseError;
import com.android.volley.toolbox.HttpHeaderParser;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Custom Request Class for JSON
*/
public class CustomRequest extends Request<JSONObject> {
private List params; // the request params
private Response.Listener<JSONObject> listener; // the response listener
public CustomRequest(int requestMethod, String url, List params,
Response.Listener<JSONObject> responseListener, Response.ErrorListener errorListener) {
super(requestMethod, url, errorListener); // Call parent constructor
this.params = params;
this.listener = responseListener;
}
// We have to implement this function
@Override
protected void deliverResponse(JSONObject response) {
listener.onResponse(response); // Call response listener
}
// Proper parameter behavior
@Override
public Map <String, String> getParams() throws AuthFailureError {
Map <String, String> map = new HashMap <String, String>();
// Iterate through the params and add them to our HashMap
for (BasicNameValuePair pair: params) {
map.put(pair.getName(), pair.getValue());
}
return map;
}
// Same as JsonObjectRequest#parseNetworkResponse
@Override
protected Response<JSONObject> parseNetworkResponse(NetworkResponse response) {
try {
String jsonString = new String(response.data, HttpHeaderParser.parseCharset(response.headers));
return Response.success(new JSONObject(jsonString),
HttpHeaderParser.parseCacheHeaders(response));
} catch (UnsupportedEncodingException e) {
return Response.error(new ParseError(e));
} catch (JSONException je) {
return Response.error(new ParseError(je));
}
}
}