Android POST Request 400 Response code throws Exception

AndroidDev picture AndroidDev · Aug 15, 2012 · Viewed 7.3k times · Source

When i send a POST Request to a Server, if the response is 200 i get the JSON body. However for unsuccessful requests the servers send a 400 response code but my android code throws a FileNotFoundException. Is there any difference between reading a 400 response and a 200 response ?

        StringBuffer responseBuilder = new StringBuffer();
    String line = null;
    HttpURLConnection conn = null;
    OutputStream out = null;
    BufferedReader rd = null;
    System.setProperty("http.keepAlive", "false");
    try
    {
        conn = (HttpURLConnection) new URL(requestURL).openConnection();
        conn.setRequestMethod("POST");
        conn.setDoOutput(true);
        conn.setDoInput(true);
        conn.setUseCaches(false);
        conn.setAllowUserInteraction(false);
        conn.setConnectTimeout(NetworkConstants.CONNECTION_TIMEOUT);
        conn.setReadTimeout(NetworkConstants.SOCKET_TIMEOUT);

        out = conn.getOutputStream();
        Writer writer = new OutputStreamWriter(out, "UTF-8");
        String s = formatParams();
        Log.d("-------------------------------------------------->", s);
        writer.write(s);
        writer.flush();
        writer.close();
    }

    catch (Exception e)
    {

    }

    finally
    {
        if (out != null)
        {
            try
            {
                out.close();
            }
            catch (IOException e)
            {
                e.printStackTrace();

            }
        }
    }
    try
    {
        rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        while ((line = rd.readLine()) != null)
        {
            responseBuilder.append(line);
            if (!rd.ready())
            {
                break;
            }
        }
    }
    catch (Exception e)
    {
        e.printStackTrace();
    }

    finally
    {
        if (conn != null)
        {
            conn.disconnect();
        }
    }

    String response = responseBuilder.toString();
    Log.d("@@@@@@@@@@@@@@@@@@@@@@@@@@@", response);
    return response;

Kind Regards,

Answer

Carsten Hagemann picture Carsten Hagemann · Dec 4, 2015

Use getErrorStream() for this. From the docs:

If the HTTP response indicates that an error occurred, getInputStream() will throw an IOException. Use getErrorStream() to read the error response. The headers can be read in the normal way using getHeaderFields().

Sample code:

        httpURLConnection.connect();

        int responseCode = httpURLConnection.getResponseCode();
        if (responseCode >= 400 && responseCode <= 499) {
            Log.e(TAG, "HTTPx Response: " + responseCode + " - " + httpURLConnection.getResponseMessage());
            in = new BufferedInputStream(httpURLConnection.getErrorStream());
        }
        else {
            in = new BufferedInputStream(httpURLConnection.getInputStream());
        }

        BufferedReader reader = new BufferedReader(new InputStreamReader(in));
        String line = "";
        while ((line = reader.readLine()) != null) {
            urlResponse.append(line);
        }