Is it possible to get the status code and the body value
See original GitHub issueHello,
I am trying to do a post request, and my api send back an status number and a string that tells me if it succeeded, or if it failed and for wat reason.
I tried multiple ways, with my last one being
@Override
public Single<JSONObject> createAnAnimal(NewAnimalRequest newAnimalRequest) {
return Rx2AndroidNetworking.post(ApiEndPoint.PUT_CREATE_AN_ANIMAL)
.addBodyParameter(newAnimalRequest)
.build()
.getJSONObjectSingle();
}
which gets called from
getDataManager()
.createAnAnimal(new NewAnimalRequest(/**allot of data**/))
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new SingleObserver<JSONObject>() {
@Override
public void onSubscribe(Disposable d) {
}
@Override
public void onSuccess(JSONObject jsonObject) {
}
@Override
public void onError(Throwable e) {
}
});
}
But its seems to throw an error (ParseError: org.json.JSONException: Value Some object or text of type java.lang.String cannot be converted to JSONObject). I did also try the getAsOkHttpResponse, but its requires an OkHttpListener, and i can’t use that instead o just want to send it back to my original caller.
Is there anyways to accomplish this? Or how would it be recommended to handle positive responses from a post request?
using postman the return looks like
Status: 202 Accepted Body: “Some object or text”
That being said, when i use this same code but instead return a failed status like
Status: 406 Not Acceptable Body: “Some object or text”
It nicely triggers the onError, and displays the error code and the body containing the string.
So just to clarify what my idea was, is that for a positive status response the on success triggers, and i can do wat i need to do, and when its a negative response it just triggers the onError like it already does.
Issue Analytics
- State:
- Created 5 years ago
- Comments:5 (1 by maintainers)
Top GitHub Comments
Try with
getStringSingle
and for getting both in one listener usegetAsOkHttpResponseAndString
I was unable to find a perfect solution, but this is how i got it to work.
We call the api from where ever in the project, I would not be able to use the
getOkHttpResponse
, mainly because this requires a new listener as parameter, meaning that they listening for a response is done in the Api manager class, not the class where i actually need the response.For this i opted to use the
getStringSingle
instead, even tho i don’t need it, it allows me to handle a successful add and error. The server on sucsess sends back an positivehttpResponse
, this will trigger theonSucsess
with an empty string and then i can do wat ever i want, in my case close the fragment.But when the server throws a bad request and a string of the issue it triggers the
onError
. The issue here is that your unable to read out the error boddy and code from athrowable
, thats where thehandleError(e);
comes into play