| Get response body from a URL as a String This will download text data from the specified URL, and return it as a String. How this works:
First, we create a `HttpUrlConnection` from our URL, with `new URL(url).openConnection()`. We cast the `UrlConnection` this returns to a `HttpUrlConnection`, so we have access to things like adding headers (such as User Agent), or checking the response code. (This example does not do that, but it's easy to add.)
Then, create `InputStream` basing on the response code (for error handling)
Then, create a `BufferedReader` which allows us to read text from `InputStream` we get from the connection.
Now, we append the text to a `StringBuilder`, line by line.
Close the `InputStream`, and return the String we now have.
Notes:
This method will throw an `IoException` in case of failure (such as a network error, or no internet connection), and it will also throw an **unchecked** `MalformedUrlException` if the given URL is not valid.
It can be used for reading from any URL which returns text, such as webpages (HTML), REST APIs which return JSON or XML, etc.
See also: [Read URL to String in few lines of Java code](http://stackoverflow.com/questions/4328711/read-url-to-string-in-few-lines-of-java-code).
Usage: Is very simple: |
| Delete resource This will DELETE the resource in the specified URL, then print the response header. How it works - we obtain the
HttpURLConnection from a URL. - Set the content type using
setRequestProperty, by default it's application/x-www-form-urlencoded setDoInput(true) tells the connection that we intend to use the URL connection for input. setRequestMethod("DELETE") to perform HTTP DELETE At last we print the server response header. |
Check if resource exists Explanation: If you are just checking if a resource exists, it better to use a HEAD request than a GET. This avoids the overhead of transferring the resource. Note that the method only returns true if the response code is 200. If you anticipate redirect (i.e. 3XX) responses, then the method may need to be enhanced to honor them. Example:
Using HttpUrlConnection on Android requires that you add the Internet permission to your app (in the `AndroidManifest.xml`).
There are also other Java HTTP clients and libraries, such as Square's [OkHttp](http://github.com/square/okhttp/), which are easier to use, and may offer better performance or more features.
|