question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Is it possible to get the status code and the body value

See original GitHub issue

Hello,

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:open
  • Created 5 years ago
  • Comments:5 (1 by maintainers)

github_iconTop GitHub Comments

1reaction
amitshekhariitbhucommented, Jun 17, 2018

Try with getStringSingle and for getting both in one listener use getAsOkHttpResponseAndString

0reactions
ghostcommented, Jun 19, 2018

I was unable to find a perfect solution, but this is how i got it to work.

getDataManager()
               .createAnAnimal(new NewAnimalRequest(/**some variables*/))
               .subscribeOn(Schedulers.io())
               .observeOn(AndroidSchedulers.mainThread())
               .subscribe(new SingleObserver<String>() {
                   @Override
                   public void onSubscribe(Disposable d) {

                   }

                   @Override
                   public void onSuccess(String s) {
                       //Do wat ever needs to be done on sucsess
                       getNavigator().goBack();

                   }

                   @Override
                   public void onError(Throwable e) {
                       getNavigator().handleError(e); 
                   }
               });

 @Override
    public Single<String> createAnAnimal(NewAnimalRequest newAnimalRequest) {
        return Rx2AndroidNetworking.post(ApiEndPoint.PUT_CREATE_AN_ANIMAL)
                .addBodyParameter(newAnimalRequest)
                .build()
                .getStringSingle();
    }

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 positive httpResponse, this will trigger the onSucsess 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 a throwable, thats where the handleError(e); comes into play


@Override
    public void handleError(Throwable throwable) {
        if(throwable instanceof ANError) {
            ANError anError = (ANError) throwable;
            if(anError.getErrorCode() != 0) {
                Toast.makeText(getActivity(), anError.getErrorBody(), Toast.LENGTH_LONG).show();
            } else {
                Toast.makeText(getActivity(), anError.getErrorDetail(), Toast.LENGTH_LONG).show();
            }
        } else {
            Toast.makeText(getActivity(), throwable.getMessage(), Toast.LENGTH_LONG).show();
        }
    }

handleError will take a throwable and check if it is an instance of `ANError`, which in case of an `httpResponse` error it is. then after converting it we will be able to read it out, when it is not an `AnError `your able to print the `getMessage()` like normaly.
Read more comments on GitHub >

github_iconTop Results From Across the Web

Status codes in HTTP - W3C
These codes indicate success. The body section if present is the object returned by the request. It is a MIME format object. It...
Read more >
How do I retrieve HTTP status code and response body when ...
HttpClientErrorException provides getStatusCode and getResponseBodyAsByteArray to get the status code and body, respectively.
Read more >
HTTP response status codes - MDN Web Docs - Mozilla
HTTP response status codes indicate whether a specific HTTP request has been successfully completed. Responses are grouped in five classes:
Read more >
Getting curl to output HTTP status code? - Super User
This should work for you if the web server is able to respond to HEAD requests (this will not perform a GET request):...
Read more >
HTTP Status Codes: All 63 explained - including FAQ & Video
HTTP status codes are three-digit responses from the server to the browser-side request. Everyone has probably gotten the classic 404 page-not-found error.
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found