# HttpURLConnection
# Get response body from a URL as a String
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.
# POST data
public static void post(String url, byte [] data, String contentType) throws IOException {
HttpURLConnection connection = null;
OutputStream out = null;
InputStream in = null;
try {
connection = (HttpURLConnection) new URL(url).openConnection();
connection.setRequestProperty("Content-Type", contentType);
connection.setDoOutput(true);
out = connection.getOutputStream();
out.write(data);
out.close();
in = connection.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
String line = null;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
in.close();
} finally {
if (connection != null) connection.disconnect();
if (out != null) out.close();
if (in != null) in.close();
}
}
This will POST data to the specified URL, then read the response line-by-line.
# How it works
- As usual we obtain the
HttpURLConnectionfrom aURL. - Set the content type using
setRequestProperty, by default it'sapplication/x-www-form-urlencoded setDoOutput(true)tells the connection that we will send data.- Then we obtain the
OutputStreamby callinggetOutputStream()and write data to it. Don't forget to close it after you are done. - At last we read the server response.
# Delete resource
public static void delete (String urlString, String contentType) throws IOException {
HttpURLConnection connection = null;
try {
URL url = new URL(urlString);
connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.setRequestMethod("DELETE");
connection.setRequestProperty("Content-Type", contentType);
Map<String, List<String>> map = connection.getHeaderFields();
StringBuilder sb = new StringBuilder();
Iterator<Map.Entry<String, String>> iterator = responseHeader.entrySet().iterator();
while(iterator.hasNext())
{
Map.Entry<String, String> entry = iterator.next();
sb.append(entry.getKey());
sb.append('=').append('"');
sb.append(entry.getValue());
sb.append('"');
if(iterator.hasNext())
{
sb.append(',').append(' ');
}
}
System.out.println(sb.toString());
} catch (Exception e) {
e.printStackTrace();
} finally {
if (connection != null) connection.disconnect();
}
}
This will DELETE the resource in the specified URL, then print the response header.
# How it works
- we obtain the
HttpURLConnectionfrom aURL. - Set the content type using
setRequestProperty, by default it'sapplication/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
/**
* Checks if a resource exists by sending a HEAD-Request.
* @param url The url of a resource which has to be checked.
* @return true if the response code is 200 OK.
*/
public static final boolean checkIfResourceExists(URL url) throws IOException {
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("HEAD");
int code = conn.getResponseCode();
conn.disconnect();
return code == 200;
}
# 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:
checkIfResourceExists(new URL("http://images.google.com/")); // true
checkIfResourceExists(new URL("http://pictures.google.com/")); // false