How to make a JSON request in volley where I need to send an authentification header and JSON object in body and I expect only an status code 200 answer
JsonObjectRequest request = new JsonObjectRequest(
method,
url,
myJsonObject,
responseListener,
errorListener) {
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<String, String>();
String creds = String.format("%s:%s", login, password);
String auth = "Basic " + Base64.encodeToString(creds.getBytes(), Base64.DEFAULT);
headers.put("Authorization", auth);
return headers;
}
};
new Response.Listener<String>(){
@Override
public void onResponse(String response) {
Toast.makeText(getActivity(), response, 1000).show();
}
I tried different kinds of response listeners with string or JSON object, object, but always there is an error: android volley org.json.JSONException: End of input at character 0 of
Or is there any other kind of request in volley which supports and json object and authentification header in body and response is just a http status code ?
I know its an old question but i thought i still answer this as my answer might help people in future -
You need to create a custom class that extends Request class and in that class override these methods
@Override
protected Response parseNetworkResponse(NetworkResponse response) {
return Response.success(response.statusCode, HttpHeaderParser.parseCacheHeaders(response));
}
@Override
protected void deliverResponse(Integer statusCode) {
mListener.onResponse(statusCode);
}
This is the heart and soul of the class.
For full code and explanation check out my blog on the topic -
Getting a server response status 200 from Android Volley library
link 1
Hope it helps, Thanks
Thanks to Varundroid and Itai Hanski. It's correct, you just need to subclass the JsonObjectRequest.
For convenience here's my override:
public class MyJsonObjectRequest extends JsonObjectRequest {
@Override
protected Response<JSONObject> parseNetworkResponse(NetworkResponse response) {
try {
String jsonString = new String(response.data, HttpHeaderParser.parseCharset(response.headers));
// here's the new code, if jsonString.length() == 0 don't parse
if (jsonString.length() == 0) {
return Response.success(null, HttpHeaderParser.parseCacheHeaders(response));
}
// end of patch
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));
}
}
}
So I just use that instead of JsonObjectRequest
.
Not too pretty, not too ugly.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With