Playing around with the Volley library, I noticed that when making a POST JsonObjectRequest
, if the server returns a code 304 or 200 with no data in the response (response.data)
, Volley interprets it as an error response, instead of a success.
I manage to solve it by adding a couple of lines of code in the method Response<JSONObject> parseNetworkResponse(NetworkResponse response)
in the class 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));
}
}
Is it the best solution for this problem?
Thanks!
EDIT
Checking the class BasicNetwork.java
I realized that Volley checks if a response has no data by asking 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];
}
But the problem is still the JSONException that occurs when Volley tries to create a new string with response.data == new byte[0]
in the parseNetworkResponse method.