在使用 Volley 库时,我注意到在进行 POST 时JsonObjectRequest
,如果服务器返回代码 304 或 200 且响应中没有数据(response.data)
,Volley 会将其解释为错误响应,而不是成功。
Response<JSONObject> parseNetworkResponse(NetworkResponse response)
我设法通过在类的方法中添加几行代码来解决它JsonObjectRequest.java
。
@Override
protected Response<JSONObject> parseNetworkResponse(NetworkResponse response) {
try {
if (!response.notModified) {// Added for 304 response
String jsonString = new String(response.data,
HttpHeaderParser.parseCharset(response.headers));
return Response.success(new JSONObject(jsonString),
HttpHeaderParser.parseCacheHeaders(response));
} else // Added for 304 response
return Response.success(new JSONObject(),HttpHeaderParser.parseCacheHeaders(response));
} catch (UnsupportedEncodingException e) {
Log.v("Volley", "UnsupportedEncodingException " + response.statusCode);
if (response.statusCode == 200)// Added for 200 response
return Response.success(new JSONObject(), HttpHeaderParser.parseCacheHeaders(response));
else
return Response.error(new ParseError(e));
} catch (JSONException je) {
Log.v("Volley", "JSONException " + response.statusCode);
if (response.statusCode == 200)// Added for 200 response
return Response.success(new JSONObject(),HttpHeaderParser.parseCacheHeaders(response));
else
return Response.error(new ParseError(je));
}
}
它是这个问题的最佳解决方案吗?
谢谢!
编辑
检查课程BasicNetwork.java
我意识到 Volley 通过询问 if 来检查响应是否没有数据httpResponse.getEntity() != null
。
// Some responses such as 204s do not have content. We must check.
if (httpResponse.getEntity() != null) {
responseContents = entityToBytes(httpResponse.getEntity());
} else {// Add 0 byte response as a way of honestly representing a
// no-content request.
responseContents = new byte[0];
}
但问题仍然是当 Volley 尝试response.data == new byte[0]
在 parseNetworkResponse 方法中创建新字符串时发生的 JSONException。