Reputation: 2401
I'm trying to get a response body from a HttpUrlConnection object when my server doesn't return a 200 OK. In my case, I get a 302 redirect and so using getInputStream()
doesn't work. I tried to use getErrorStream()
but this gives me a null object for some reason. Why am I getting a null object for getErrorStream()
when I'm expecting an actual response?
public static void main(String[] args) {
String url = "http://www.google.com/";
String proxy = "proxy.myproxy.com";
String port = "8080";
try {
URL server = new URL(url);
Properties systemProperties = System.getProperties();
systemProperties.setProperty("http.proxyHost",proxy);
systemProperties.setProperty("http.proxyPort",port);
HttpURLConnection connection = (HttpURLConnection)server.openConnection();
connection.connect();
System.out.println("Response code:" + connection.getResponseCode());
System.out.println("Response message:" + connection.getResponseMessage());
InputStream test = connection.getErrorStream();
String result = new BufferedReader(new InputStreamReader(test)).lines().collect(Collectors.joining("\n"));
} catch (Exception e) {
System.out.println(e);
System.out.println("error");
}
}
In my code, what I'm seeing as output is:
Response code:302
Response message:Object Moved
java.lang.NullPointerException
error
Specifically, the error occurs in the last line of my try clause because it's my getErrorStream()
returns a null object and hence I get a nullPointerException. Is anyone familiar with this? Thanks
Upvotes: 3
Views: 8118
Reputation: 1
package com.ketal.pos.sevice;
import com.utsco.model.User;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import javax.net.ssl.HttpsURLConnection;
/**
*
* @author Jose Luis Uyuni
*/
public class GenericService {
private static final long serialVersionUID = 0L;
public static final String HTTPS = "https";
public static final String HTTP = "http";
public String port;
public static String protocolo = HTTP + "://";
public String dominio;
private String urlBase = protocolo;
public String urlService;
public Integer response;
public String getPort() {
return port;
}
public void setPort(String port) {
this.port = port;
}
public String getDominio() {
return dominio;
}enter code here
public void setDominio(String dominio) {
this.dominio = dominio;
}
public String getUrlBase() {
return urlBase;
}
public String getUrlService() {
return urlService;
}
public void setUrlService(String urlService) {
this.urlService = urlService;
}
public String getStringResponse(User u, String method, String query, String body) throws MalformedURLException, IOException, Exception {
String response = null;
this.urlBase = protocolo + dominio + urlService + query;
URL url = new URL(urlBase);
HttpURLConnection conn;
if (protocolo.contains(HTTPS)) {
conn = (HttpsURLConnection) url.openConnection();
} else {
conn = (HttpURLConnection) url.openConnection();
}
conn.setRequestMethod(method);
conn.setRequestProperty("Accept", "application/json");
conn.setRequestProperty("content-type", "application/json; charset=UTF-8");
if (u != null) {
conn.setRequestProperty("Authorization", "Basic " + javax.xml.bind.DatatypeConverter.printBase64Binary(("ketal.org" + ":" + "124578").getBytes()));
}
if (!method.equalsIgnoreCase("GET")) {
conn.setDoOutput(true);
conn.setRequestProperty("Content-Length", Integer.toString(body.length()));
conn.setRequestProperty("body", body);
}
response = "";
if (conn.getResponseCode() != 200) {
if (conn.getErrorStream() != null) {
response = getResponse(conn.getErrorStream());
}
if (response.equals("")) {
response = "{\"message\": \"error\" , \"state\": \"error\", \"nroErr\" ;\"" + "0" + "\" }]";
}
} else {
response = getResponse(conn.getInputStream());
}
conn.disconnect();
return response;
}
public String getResponse(InputStream i) throws IOException {
String res = "";
InputStreamReader in = new InputStreamReader(i);
BufferedReader br = new BufferedReader(in);
String output;
while ((output = br.readLine()) != null) {
res += (output);
}
return res;
}
}
Upvotes: 0
Reputation: 44368
Because 302
is not considered as an error HTTP response code.
3XX
codes are the Redirection responses4XX
codes are the Client error responses5XX
codes are the Server error responsesSince the response does not start with 4
nor 5
, it is not considered as an erroneous one.
Also look at the documentation of HttpURLConnection::getErrorStream
:
Returns the error stream if the connection failed but the server sent useful data nonetheless. The typical example is when an HTTP server responds with a 404, which will cause a FileNotFoundException to be thrown in connect, but the server sent an HTML help page with suggestions as to what to do.
Feel free to dig into the source code as well to get the more information and where is everything clear:
@Override
public InputStream getErrorStream() {
if (connected && responseCode >= 400) {
// Client Error 4xx and Server Error 5xx
if (errorStream != null) {
return errorStream;
} else if (inputStream != null) {
return inputStream;
}
}
return null;
}
Sadly, this information is not included in the documentation, though.
Upvotes: 4