The getResponseMessage is a method of Java HttpURLConnection class. This method is used to get response code from HTTP response message. For example, if the response code from a server is HTTP/1.0 200 OK or HTTP/1.0 404 Not Found, it extracts the string OK and Not Found else returns null if HTTP is not valid.
Call setRequestProperty() method on HttpURLConnection instance to set request header values, such as “User-Agent” and “Accept-Language” etc. We can call getResponseCode() to get the response HTTP code.
Java HttpURLConnection getErrorStream() Method The getErrorStream() is the method of HttpURLConnection class. This method is used to get an error stream if the connection is disconnected. This method does not set the connection.
If the response code isn't 200 or 2xx, use getErrorStream()
instead of getInputStream().
Wrong method was used for errors, here is the working code:
BufferedReader br = null;
if (100 <= conn.getResponseCode() && conn.getResponseCode() <= 399) {
br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
} else {
br = new BufferedReader(new InputStreamReader(conn.getErrorStream()));
}
This is an easy way to get a successful response from the server like PHP echo otherwise an error message.
BufferedReader br = null;
if (conn.getResponseCode() == 200) {
br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String strCurrentLine;
while ((strCurrentLine = br.readLine()) != null) {
System.out.println(strCurrentLine);
}
} else {
br = new BufferedReader(new InputStreamReader(conn.getErrorStream()));
String strCurrentLine;
while ((strCurrentLine = br.readLine()) != null) {
System.out.println(strCurrentLine);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With