HttpConnection Java / HttpsConnection error input / stream

In java, how do you know if you have an error stream from an Http connection or if it is an InputStream? The only way I can do this is to go both to that and to check, and to the absence of any exceptions.

HttpConnection con = (HttpConnection)URL.openConnection(); //Write to output InputStream in = con.GetInputStream(); //Vs InputStream error = con.getErrorStream(); 

How does java determine which thread it has? Is this the sole reason for the connection response code? So, if its> = 200 and <300, then its inputStream otherwhise its errorStream?

Thanks.

+4
source share
2 answers

HTTP_INTERNAL_ERROR (500) is not the only response code that can create a stream of errors, there are many others: 400, 401, 402, 403, 404, 405, 406, 407, 408, 409, 410, 411, 412, 413, 414, 415, 501, 502, 503, 504, 505, etc.

Not only that, but connection.getResponseCode() can throw an exception if it triggered a connection, and the HTTP response status code was an error class status code. Therefore, checking for 500 (HTTP_INTERNAL_ERROR) immediately after connection.getResponseCode() can be really unreachable code, depending on how you access the connection .

The strategy I saw is using an error stream if an exception was thrown, otherwise use the input stream. The following code provides a basic constructive starting point. You probably want to add to it.

 InputStream responseStream = null; int responseCode = -1; IOException exception = null; try { responseCode = connection.getResponseCode(); responseStream = connection.getInputStream(); } catch(IOException e) { exception = e; responseCode = connection.getResponseCode(); responseStream = connection.getErrorStream(); } // You can now examine the responseCode, responseStream, and exception variables // For example: if (responseStream != null) { // Go ahead and examine responseCode, but // always read the data from the responseStream no matter what // (This clears the connection for reuse). // Probably log the exception if it not null } else { // This can happen if eg a malformed HTTP response was received // This should be treated as an error. The responseCode variable // can be examined but should not be trusted to be accurate. // Probably log the exception if it not null } 
+5
source

You can do it as follows:

 InputStream inStream = null; int responseCode = connection.getResponseCode(); if (responseCode == HttpURLConnection.HTTP_INTERNAL_ERROR) { inStream = connection.getErrorStream(); } else{ inStream = connection.getInputStream(); } 

An HTTP return code means that it is the type of stream to read.

+1
source

Source: https://habr.com/ru/post/1398681/


All Articles