Chapter 25 HTTP and Background Tasks
In FlickrFetchr.java, add implementations for getUrlBytes(String) and getUrlString(String)
(Listing 25.3).
Listing 25.3 Basic networking code (FlickrFetchr.java)
public class FlickrFetchr {
public byte[] getUrlBytes(String urlSpec) throws IOException {
URL url = new URL(urlSpec);
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
try {
ByteArrayOutputStream out = new ByteArrayOutputStream();
InputStream in = connection.getInputStream();
if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
throw new IOException(connection.getResponseMessage() +
": with " +
urlSpec);
}
int bytesRead = 0;
byte[] buffer = new byte[1024];
while ((bytesRead = in.read(buffer)) > 0) {
out.write(buffer, 0, bytesRead);
}
out.close();
return out.toByteArray();
} finally {
connection.disconnect();
}
}
public String getUrlString(String urlSpec) throws IOException {
return new String(getUrlBytes(urlSpec));
}
}
This code creates a URL object from a string – like, say, https://www.bignerdranch.com. Then it
calls openConnection() to create a connection object pointed at the URL. URL.openConnection()
returns a URLConnection, but because you are connecting to an http URL, you can cast it to
HttpURLConnection. This gives you HTTP-specific interfaces for working with request methods,
response codes, streaming methods, and more.
HttpURLConnection represents a connection, but it will not actually connect to your endpoint until you
call getInputStream() (or getOutputStream() for POST calls). Until then, you cannot get a valid
response code.
Once you create your URL and open a connection, you call read() repeatedly until your connection
runs out of data. The InputStream will yield bytes as they are available. When you are done, you close
it and spit out your ByteArrayOutputStream’s byte array.
While getUrlBytes(String) does the heavy lifting, getUrlString(String) is what you will actually
use in this chapter. It converts the bytes fetched by getUrlBytes(String) into a String. Right now, it
may seem strange to split this work into two methods. However, having two methods will be useful in
the next chapter when you start downloading image data.