Paul Paul - 7 months ago 13
Java Question

Java - Url to String with any response code

I want to get the text of a url with java.

public static String getResponseFromUrlDesktop(String url) {
try {
URL website = new URL(url);
URLConnection connection = website.openConnection();


BufferedReader in = new BufferedReader(
new InputStreamReader(
connection.getInputStream()));

StringBuilder response = new StringBuilder();
String inputLine;

while ((inputLine = in.readLine()) != null)
response.append(inputLine);

in.close();

return response.toString();
} catch (IOException e) {
e.printStackTrace();
return null;
}
}


The problem is that when I go to an URL and it gives me
java.io.IOException: Server returned HTTP response code: 400 for URL

If I open the url in broswer I get a text.
How can I always get the text of a GET request no matter the response code?

Answer

Try this:

 public static String getResponseFromUrlDesktop(String url) {

        HttpURLConnection connection = null;
        StringBuilder response = new StringBuilder();
        BufferedReader in = null;
        try {
            URL website = new URL(url);
            connection = (HttpURLConnection) website.openConnection();

            in = new BufferedReader(new InputStreamReader(
                    connection.getInputStream()));
            String inputLine;

            while ((inputLine = in.readLine()) != null)
                response.append(inputLine);

            in.close();
        } catch (IOException e) {
            try {
                if (connection.getResponseCode() >= 400) {
                    in = new BufferedReader(new InputStreamReader(
                            connection.getErrorStream()));
        //                             ^^^^^^^^^^^^^^
                    String inputLine;

                    while ((inputLine = in.readLine()) != null)
                        response.append(inputLine);

                }
            } catch (IOException e1) {
                e1.printStackTrace();
            }
        }

        return response.toString();

}