Networking Basics

You are going to have one class handle the networking in PhotoGallery. Create a new Java class and, since you will be connecting to Flickr, name this class FlickrFetchr.

FlickrFetchr will start off small with only two methods: getUrlBytes(String) and getUrlString(String). The getUrlBytes(String) method fetches raw data from a URL and returns it as an array of bytes. The getUrlString(String) method converts the result from getUrlBytes(String) to a String.

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.

Asking permission to network

One other thing is required to get networking up and running: You have to ask permission. Just as users would not want you secretly taking their pictures, they also do not want you to secretly download ASCII pictures of farm animals.

To ask permission to network, add the following permission to your AndroidManifest.xml.

Listing 25.4  Adding networking permission to manifest (AndroidManifest.xml)

<manifest
    xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.bignerdranch.android.photogallery" >

    <uses-permission android:name="android.permission.INTERNET" />

    <application
      ...
    </application>

</manifest>

When a user tries to download your app, a dialog showing these permissions is displayed. The user can then accept or deny installation.

Android treats the INTERNET permission as not dangerous, since so many apps require it. As a result, all you need to do to use this permission is declare it in your manifest. More dangerous permissions (like the one allowing you to know the device’s location) also require a runtime request. (You will read more about those in Chapter 33.)

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.237.186.170