5 - 8 - Networking - Part 1 (13-40)

6
[BLANK_AUDIO] Hi, I'm Adam Porter, and this, is Programming Mobile Applications, for Android Handheld Systems. One of the defining characteristics of modern hand held systems is that they can keep us connected and networked without tethering us to a single location. In this lesson, we'll explore the software and programming practices that you'll need to connect your applications to the network. So I'll start this lesson by discussing networking in general. That discussion will focus on connecting your applications to the internet using the Hypertext Transfer Protocol or HTTP specifically by using HTTP GET requests. After that, I'll present several classes that Android provides to support this kind of networking. And lastly, I'll discuss how your applications can process the data they receive in response to these HTTP GET requests. In particular, I'll talk about two popular data formatting languages. One, the Javascript Object Notation Language, or JSON. And two, the Extensible Markup Language, or XML. And I'll talk about how you parse, or make sense, of these HTTP responses when they're formatted in one of these languages. So early handheld devices gave us mobility. You could move from one place to another, and still perform useful computation. However, their networking capabilities were primitive by today's standards. Now moving forward, today's devices combine powerful processors with fast network connections over WiFi and cellular networks. Handheld applications will therefore often want to make use of these networking capabilities to access and provide data, and services. Now, to help you do this, Android includes a variety of networking support classes, including the Socket and URL classes, in the Java.net packages. The HttpRequest, and HttpResponse classes, in the org.apache

Transcript of 5 - 8 - Networking - Part 1 (13-40)

Page 1: 5 - 8 - Networking - Part 1 (13-40)

[BLANK_AUDIO]Hi, I'm Adam Porter, and this, isProgrammingMobile Applications, for Android HandheldSystems.One of the defining characteristics ofmodern hand held systems is that they cankeep us connected and networked withouttethering us to a single location.In this lesson, we'll explore the softwareandprogramming practices that you'll need toconnect your applications to the network.So I'll start this lesson by discussingnetworking in general.That discussion will focus on connectingyour applications to the internet usingthe Hypertext Transfer Protocol or HTTPspecifically by using HTTP GET requests.After that, I'll present several classesthatAndroid provides to support this kind ofnetworking.And lastly, I'll discuss how yourapplications can process thedata they receive in response to theseHTTP GET requests.In particular, I'll talk about two populardata formatting languages.One, the Javascript Object NotationLanguage, or JSON.And two, the Extensible Markup Language,or XML.And I'll talk about how you parse, or makesense, ofthese HTTP responses when they'reformatted in one of these languages.So early handheld devices gave usmobility.You could move from one place to another,and still perform useful computation.However,their networking capabilities wereprimitive by today's standards.Now moving forward, today's devicescombine powerful processorswith fast network connections over WiFiand cellular networks.Handheld applications will therefore oftenwant to make useof these networking capabilities to accessand provide data, andservices.Now, to help you do this, Android includesa variety of networking support classes,including the Socket and URLclasses, in the Java.net packages.The HttpRequest,and HttpResponse classes, in theorg.apache

Page 2: 5 - 8 - Networking - Part 1 (13-40)

packages.And the URI, AndroidHttpClient,and AudioStream classes, in theandroid.net packages.In this lesson we're going to look atseveral of theseclasses using each of them to implementthe same example application.And this application interacts with aninternet service to getinformation about earthquakes that haveoccurred in a particular geographicregion.And as you'll see, that data is returnedin various formats.Now initially we'll just display thedownloaded text as is.Later on in the lesson, I'll show you howtoprocess that data to extract just theinformation that you want.Oh, and, and one other thing.As you'll see in a second, becausethis data includes geographic information,it's reallybegging to be displayed on a map, ratherthan as text.Now, we won't do that in this lesson, butkeep this in mind, becausewe'll come back to this when we get to thelesson on maps and location.So in order to make this application work,the code needs to create an HTTPrequest, send it to a server computer,retrieve the results,and then display those results.Android provides several classes forhelping with this.Three we'll talk about now are the Socketclass, the HttpUrlConnection class and theAndroidHttpClient.So here's my device.And now I'll launch the networking socketapplication.Asyou can see, this application initiallydisplays a single button labeledLoad Data.When I press that button, the applicationwill issue an HTTP GET request to anexternal server.And that server will respond with somecomplex text containing the requestedearthquake data.Okay.So now I'll press the Load Data button andthere you can see the requested data.Let's look at the source code to see whatit took to get that data.Now here I've opened the application in

Page 3: 5 - 8 - Networking - Part 1 (13-40)

the IDE.Now I'll open the main activity for thisapplication.And here I'm showing the listener for theLoad Data button.When this button is pressed, theapplication will create, and then execute,an AsyncTask called HttpGetTask.Let's look at that class.The HttpGetTask class first declares somevariables,they're used in creating an HTTP GETRequest.When the execute method is called, onthe HttpGetTask, the doInBackground methodis called.And that method begins by creating a newsocket.That will be connected to the hostcomputer, api.geonames.orgon the standard http port port 80.Next, the codegets the socket's output stream, and thenwrites the HTTP_GET_COMMAND.And this string will be sent to the hostcomputer, which interprets itas an HTTPGetRequest, and then respondsby sending back the appropriate responsedata.And then this code continues by gettingthe socket's input stream Andby passing it to a method calledreadStream.The readStream method ultimately reads theresponse data from the socket'sInputStream.And then returns the response as asingle string.And this string is passed to theonPostExecute method which executes on themain thread and whichdisplays the response in the text view.If we return back to the application,you'll notice that the response textincludes not only the earthquake data, butalso the HTTP response headers.Now normally, I wouldn't want to displaythat text here.I really just want to show you theearthquake data.So in the case, I should have parsed theresponse andpulled out just the data that I wanted.In addition, you might have noticed Ididn't write any of theerror handling code that you really needto make this application robust.And these points, capture pretty well thetrade offs of using sockets.The very low level, you can write whatever

Page 4: 5 - 8 - Networking - Part 1 (13-40)

you want onthe socket but in return, you have tohandle all the manydetails of making the HTTP requests, allthe errorhandling, and all the processing of theHTTP responses.The next implementation we'll look at usesthe HttpUrlConnection class.This class provides a higher-levelinterface that handles moreof the networking details than the socketclass does.But as we'll see in a moment, it also hasa lessflexible API than our last option, the H,the Android HTTP client class.Now, having said that, I'll also point outthat the Androidteam is not actively working on theAndroid HTTP client anymore.And it's putting it's efforts intoimproving this class going forward.So let's look at the example applicationimplemented this time with theHttpURLConnection class.Sohere's my device.And now I'll launch the NetworkingURLapplication.As before, this application initiallydisplaysa single button labeled Load Data.And as before, when I press on that buttonthe application will issue an HTTPGET request To an external server, andthat server willrespond, with some complex text,containing the requested earthquake data.Okay, so now I'll press theLoad Data button.There you can see the requested data,appearing in a text view.Notice, however, that this time, the HTTPresponse headers have been stripped out.Let's look at the source code and see howthis works.Now, here I've got the application openedin the IDE.Now, I'll open the main activity for thisapplication.And here, I'm showing the listener for theload data button.As before, when this button is pressed,the application will create and thenexecute an AsyncTask called, HttpGetTask.Let's look at that class.When the execute method is called on HTTPGetTask, the doInBackgroundmethod is invoked.

Page 5: 5 - 8 - Networking - Part 1 (13-40)

That method begins by creating a new URLobject, and passing a URL string for thedesired service as a parameter.The code then calls the open connectionmethodon the URL object, which returns anhttpUrlConnection.This object is then stored in a variablecalled HttpURLConnection.The code continues by getting the HTTP URLconnection's input stream.And by passing it through the readStreammethod.And as before, the readStream method,reads the response datafrom the socket's input stream, and thenreturns the response,as a single string.This time however, the HTTP URL connectionstrips off the HTTP response headers andhandles the error checking for you.Now this string is then passed to theonPostExecutemethod which displays the response in atext view.The third class is Android HTTP client.This class is an implementation of theApache project's DefaultHttpClient and itallows a great deal of customization.In particular, the class breaks an HTTPtransaction into arequest object and into a response object.So you can create subclassesthat customize the handling of requestsand their responses.Now, by this point, you know what theapplication looks like,so let's jump straight into the code andlook at the implementation.Now, here I've got the networking AndroidHTTP client application opened in the IDE.Now, I'll open the main activity for thisapplication.And let's go right to the HTTP get taskclass.That class begins by creating a newAndroidHttpClient object by calling theclasses newInstance method.Now, when the doInBackground method iscalled, the code createsan HttpGet object, passing in the URLstring for that request.Next, it creates a response handlerobject.This object is responsible for handlingthe response to the HttpGet request.In this case, a response handler is oftype basicresponse handler.Which will return the response's body.

Page 6: 5 - 8 - Networking - Part 1 (13-40)

Now we'll see a more complex responsehandler, later in this lesson.And finally, the request and theResponseHandler, are passed into theexecute method.Which sends the request, gets theresponse, passing it through theResponseHandler.And theresult of all this is then passed on toonPostExecute.Which displays the response in a textfield.[BLANK_AUDIO]