Get response body from a URL as a String

suggest change
String getText(String url) throws IOException {
    HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
    // Add headers to the connection, or check the status, if desired.

    // Handle an error response code if one occurs.
    int responseCode = connection.getResponseCode();
    InputStream inputStream;
    if (200 <= responseCode && responseCode <= 299) {
        inputStream = connection.getInputStream();
    } else {
        inputStream = connection.getErrorStream();
    }

    BufferedReader in = new BufferedReader(
        new InputStreamReader(
            inputStream));

    StringBuilder response = new StringBuilder();
    String currentLine;

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

    in.close();

    return response.toString();
}

This downloads text from the specified URL and returns it as a String. readLine drops the line separators, so the result is the lines concatenated.

How this works:

Notes:

Usage:

String text = getText("http://example.com");
// Do something with the text from example.com, in this case the HTML.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents