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 error response code it occurs
    int responseCode = conn.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 will download text data from the specified URL, and return it as a String.

How this works:

Notes:

Usage:

Is very simple:

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