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(

    StringBuilder response = new StringBuilder();
    String currentLine;

    while ((currentLine = in.readLine()) != null) 


    return response.toString();

This will download text data from the specified URL, and return it as a String.

How this works:



Is very simple:

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

Feedback about page:

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

Table Of Contents