Scratch Space

5. Establishing Http Connections

Http connections are immensely useful for transferring data between a mobile device and a server. Such connections can be used by mobile devices for retrieving information as well as sending data back to a server. For the last section of the lab, you will be implementing functionality to share your jokes with the rest of the class. By making Http Requests, you will connect with a server to upload your own jokes and download other people's jokes.

The Android framework doesn't supply its own API for establishing connections to the internet. Instead, it includes both of the java.net and org.apache.http packages. The java.net.URL class provides a very clean and simple interface for creating an Http connection and retrieving a response. The apache.http package provides a more robust collection of classes and is not as straightforward to use.

5.1 Uploading Jokes to the Server

You will begin by adding an "Upload Joke" MenuItem to the Context Menu that gets displayed when a user long-presses/long-touches a joke. When the user selects the "Upload Joke" MenuItem, your application should send the text of the joke and the name of the Author to a server. The server will then send back a response indicating whether the joke was recieved. Your application should then notify the user that the upload succeeded or failed via a Toast Notification.

5.1.1 Update Your Manifest

Accessing the Internet requires your application to have permission to use the internet. Your application must declare in its manifest that it uses the internet. When the application gets installed, the user is presented with a list of permissions that the application says it will use. At this point, the user will have the option to grant the application these permissions, or deny these permissions and cancel the installation.

Add the following line to your AndroidManifest.xml file:

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

It should be nested between the root <manifest></manifest> tags, one level deep, at the same level as your <application></application> tags. It should look something like this:

<manifest ... >

...

<application ...>

        ...

</application>

...

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

</uses-permission>

...

</manifest>

5.1.2 Add "Upload Joke" Context MenuItem

In your onCreateContextMenu(...) method:

Add a new MenuItem to the context menu, initializing its text to "Upload Joke to Server".

  • You MUST assign this MenuItem an ID of AdvancedJokeList.UPLOAD_JOKE_MENUITEM and use the R.string.upload_menuitem resource for its title.

Set the MenuItem's OnClickListener:

  • The OnClickListener should call the uploadJokeToServer(...) method, passing in the Joke that was long-pressed.
  • Feel free to use either an anonymous inner class or make AdvancedJokeList implement the OnMenuItemClickListener interface.

5.1.3 Fill in "uploadJokeToServer(Joke joke)" Method

You will have to test for and catch any Exceptions that are thrown by using classes from the java.net package. You don't have to do anything special should an exception be thrown, just exit the method gracefully. Feel free to print out whatever exception information you feel may be of use. This would be a great time to use Log.

Begin by constructing a string that will contain the complete URL you will use to submit your Joke to the server:

The base URL to the addJoke script is:

http://simexusa.com/aac/addOneJoke.php?

Append to this a parameter named joke, containing the UTF-8 encoded text of your Joke.

  • Use the static method java.net.URLEncoder.encode(...) to perform the encoding.
    • This method takes in a string containing the text it should encode, and a string containing the type of encoding it should use.
    • It will then return a "UTF-8" encoded string containing the text you passed in. For instance, this method will replace spaces with "+" characters.
  • Use "UTF-8" as the encoding string.

Append to this another parameter named author, containing the UTF-8 encoded Author's name.

Separate this parameter from the previous one with an "&"

character.

  • Be sure to use the author name from the joke which you retrieved from res/values/strings.xml.

DO NOT encode the parameter names, only their values. (i.e. "joke=" should not be encoded).

Your URL should look something like this when finished:

http://simexusa.com/aac/addOneJoke.php?joke=This+is+my+joke&author=reed

Make your Http connection and read the response from the server:

Create a new java.net.URL Object by passing in your complete URL string into the constructor.

  • This will establish the connection to the server and submit your joke.
  • An example of using the URL class can be found here...

call openStream() on your URL Object to read the response from the server.

  • This will return an InputStream from which you will have to parse the server response.
  • Read the entire response from the server into a string object. Do this however you like. As a suggestion, the java.util.Scanner class can be constructed from an InputStream object and provides a nice interface for parsing.

Test the response and notify the user of success or failure:

Compare the response from the server:

If you succeeded the server will send back a message with the text of

"1 record added"

  • Any other response is considered a failure.

Create an android.widget.Toast notification:

  • If your upload was successful, display the text "Upload Succeeded!"
  • If your upload failed, display the text "Upload Failed!"
  • Do this by using the static Toast.makeText(...) method.
  • Call the show() method on the returned Toast object to display the notification.

Run your application and ensure that you can successfully upload jokes to the server.

5.2 Downloading Jokes from the Server

Your final task is to add a "Download Jokes" Options MenuItem. When the MenuItem is clicked your application will download all the jokes from a server and display them in the list of jokes. You don't have to display the progress indicator dialog box that is shown in the screen shots below.

5.2.1 Add "Download Jokes" Options MenuItem

Add a "Download Jokes" MenuItem to your menu.xml layout file:

You MUST assign the MenuItem a Resource ID of "download_menuitem" and use the Resource "download_menuitem" String.

When the MenuItem is clicked it should make a call the AdvancedJokeList.getJokesFromServer() method.

5.2.2 Fill in "getJokesFromServer()" Method

Construct a new URL object:

The URL string to download the jokes is

"http://simexusa.com/aac/getAllJokes.php"

This URL takes an optional UTF-8 encoded parameter named author, containing the Author's name. You may use your name.

    • When this parameter is omitted, all the jokes on the server will be retrieved. This could be a lot of jokes by the time you perform this exercise.
    • By supplying the author parameter you will only download jokes whose author matches the value supplied.

Parse the response:

The jokes returned to you by the server come in the form of a single string with each joke separated by a new-line character, '\n'.

Parse the jokes text from the InputStream

    • I would recommend the Scanner class. In particular the useDelimeter function is quite helpful.

Add the jokes to your joke list and display them.

Run your application and ensure that you can successfully download jokes from the server.