0
votes

I wrote an API in laravel, to accept POST request to receive parameters and save it in DB.

On success it responds back with a json returning the Order ID (Http response code 200)

{
    "data": {
        "order_id": 21
    }
}

before it saves data in DB I validate the data and if there is a error it returns error message json (Http response code 400)

{
    "error": {
        "code": "GEN-WRONG-ARGS",
        "http_code": 400,
        "message": {
            "cust_id": [
                "The cust id may not be greater than 9999999999."
            ]
        }
    }
}

It works perfectly fine in browser

In Android call, when it is all ok e.g. http response code 200 I get the json.

But when error json is returned I never receive the error json, getInputStream() returns null.

private InputStream downloadUrl(String urlString) throws IOException {
    // BEGIN_INCLUDE(get_inputstream)
    URL url = new URL(urlString);
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setReadTimeout(10000 /* milliseconds */);
    conn.setConnectTimeout(15000 /* milliseconds */);
    conn.setRequestMethod("GET");
    conn.setDoInput(true);
    // Start the query
    conn.connect();
    InputStream stream = conn.getInputStream();
    return stream;
    // END_INCLUDE(get_inputstream)
}
  1. If there is error how can I change response code to 200 and send it in Laravel and then get the error json.
  2. or in Android wow can I receive http body even if there is a response code like 400 or 404, like browsers get

1 is a workaround and 2 is the right way to do it.

Thanks,

K

1
Can anyone please help, with this?karmendra

1 Answers

1
votes

After hours of struggle, I figured out the solution. getErrorStream() is the solution to this. I changed the code as following to get the error response if response code>=400.

private InputStream downloadUrl(String urlString) throws IOException {
// BEGIN_INCLUDE(get_inputstream)
URL url = new URL(urlString);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(10000 /* milliseconds */);
conn.setConnectTimeout(15000 /* milliseconds */);
conn.setRequestMethod("GET");
conn.setDoInput(true);
// Start the query
conn.connect();
InputStream stream  = null;
    try {
        //Get Response
        stream = conn.getInputStream();
    } catch (Exception e) {
        try {
            int responseCode = conn.getResponseCode();
            if (responseCode >= 400 && responseCode < 500)
                stream = conn.getErrorStream();
            else throw e;
        } catch (Exception es) {
            throw es;
        }
    }
return stream;
// END_INCLUDE(get_inputstream)
}

Hope this will save someone tons of time

Thanks, K