好的,我找到了答案。 JsonObjectRequest
/JsonArrayRequest
以額外的JsonObject
/JsonArray
對象作爲參數。在大多數在線示例代碼中,這個參數設置爲null,並且我做了同樣的事情,因爲我不想發送Json,只能接收。 現在Volley Json請求的幕後發生了什麼(相當不直觀),是如果此參數爲null,則請求不會作爲POST
請求完成,而是作爲GET
取代。這導致我的請求失敗,服務器返回錯誤代碼而不是JSON。反過來,這樣的錯誤代碼無法解析爲json。 我在Volley中找到一個默認實現的非常糟糕的選擇。
在任何情況下,該解決方案是作爲引入CustomJsonObjectRequest
這非常類似於從庫中實施,不同之處在於它與POST
請求棒容易:
public class CustomJsonObjectRequest extends Request<JSONObject> {
protected static final String PROTOCOL_CHARSET = "utf-8";
private final Response.Listener<JSONObject> mListener;
public CustomJsonObjectRequest(String url, Response.Listener<JSONObject> listener, Response.ErrorListener errorListener) {
super(Method.POST, url, errorListener);
mListener = listener;
}
@Override
protected Response<JSONObject> parseNetworkResponse(NetworkResponse response) {
try {
String jsonString = new String(response.data,
HttpHeaderParser.parseCharset(response.headers, PROTOCOL_CHARSET));
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));
}
}
@Override
protected void deliverResponse(JSONObject response) {
mListener.onResponse(response);
}
}