Get response body from a URL as a String
suggest changeString 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:
- Create an
HttpURLConnectionwithnew URL(url).openConnection(), then cast theURLConnection. The cast throwsClassCastExceptionif the URL is not HTTP or HTTPS. The cast is what exposes response codes and error streams. This example checks the response code. - Choose the
InputStreamfrom the response code.getErrorStream()can return null, and a null stream fails in theInputStreamReaderconstructor. - Read text with a
BufferedReader.InputStreamReaderwith no charset uses the platform default, not the HTTPContent-Typecharset. - Append each line to a
StringBuilder. - Close the reader and return the string.
Notes:
- The method throws the checked exception
IOExceptionon failure (network error, and alsoMalformedURLException, which is a subclass ofIOException, whenurlis not a valid URL). - It can read any URL that returns text, such as HTML pages or REST APIs that return JSON or XML.
- See also: Read URL to String in few lines of Java code.
Usage:
String text = getText("http://example.com");
// Do something with the text from example.com, in this case the HTML.
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents