Wednesday, September 18, 2013

Connecting to the URL

Today I will be adding to my Blog App by getting data from the web and putting it into my app.

The way we do this is that

1)  We get data from the web
2)  Request data from the world wide web
3) Parse the response
4)Handle errors

If something goes wrong we throw an exception which lets us know something is wrong.

public static final int NUMBER_OF_POST = 20;  /*final constant number that doesn't change; can use 20 in multiple places and only have to update in one place*/
    public static final String TAG = MainListActivity.class.getSimpleName(); /* variables are in all caps b/c it lets us know that these variables hold constant variables and cannot be changed */

The way we find this is by using:  malFormedUrl exception which This exception is thrown when a program attempts to create an URL from an incorrect specification.

We also use the method URL:  Uniform Resource Locator that identifies the location of an Internet resource as specified by RFC 1738.

Putting it together we have:


        try{
            URL blogFeedUrl = new URL("http://blog.teamtreehouse.com/api/get_recent_summary/?count=" + NUMBER_OF_POST);
            }
            catch(MalformedURLException e){
                Log.e(TAG, "Exception caught: ", e);
            }

For more try catch block examples and proper practices visit:
http://source.android.com/source/code-style.html
MalformedURL method
http://developer.android.com/reference/java/net/MalformedURLException.html
URL method
http://developer.android.com/reference/java/net/URL.html

Questions:

Inside onCreate(), declare a URL variable named "treehouseUrl" and initialize it with the URL constructor, using the "URL" member variable as the parameter. Put this line inside a "try" block and then catch a MalformedURLException named "e". Don't do anything in the "catch" block yet.

      try{
      URL treehouseURL = new URL(URL);
      }
      catch(MalformedURLException e){
        Log.e("DOG", "Exception caught: ", e);  // e catches the exception, param 2 is a string, param 1 is a string
      }



try{
            URL blogFeedUrl = new URL("http://blog.teamtreehouse.com/api/get_recent_summary/?count=" + NUMBER_OF_POST);
            HttpURLConnection connection = (HttpURLConnection) blogFeedUrl.openConnection();
            connection.connect();
           
            int responseCode = connection.getResponseCode();
            Log.i(TAG, "Code: " + responseCode);
        }
            catch(MalformedURLException e){ /*only executed when there is a malformed URL, try to create a URL object then run extra code */
                Log.e(TAG, "Exception caught: ", e);
            }
           catch(IOException e){
               Log.e(TAG, "Exception caught: ", e);
           }
        catch(Exception e){
            Log.e(TAG, "Exception caught: ", e);   /*a catch of a generic exception will catch everything and none of the other catch blocks would be used */
        }

 Network connections:  2 kinds

1)HttpURLConnection  2) Apache HTTP Client 

1)HTTP URL Connection 

  • Lightweight HTTP application
  • Suitable for most applications
  • Automatically connects to SNI (server name indication) allows multiple HTTPS host to share an IP address
  • Fully cached responses from local storage (Because no network connection needs to be made such responses are available immediately.)
  • uncached responses are from the internet, placed in the response cache from the internet

2) Apache HTTP Client

  • 1) Large API; hard to improve
  • 2) Implementation is stable
  • 3) Android team working sparsely on it

HTTP URL CONNECTION vs Apache HTTP Client: 

    which to use:

  • Use Apache HTTP Client for Eclair and Froyo
  • Use HttpURLConnection for Gingerbread and above

Using HTTPConnection:
http://developer.android.com/reference/java/net/HttpURLConnection.html
Using IO Exceptions:
http://developer.android.com/reference/java/io/IOException.html
Choosing the right Client for your app:
android-developers.blogspot.com/2011/09/androids-http-clhttp://android-developers.blogspot.com/2011/09/androids-http-clients.htmlients.html


Questions:

Inside the "try" block, add an HttpURLConnection variable named "connection". Initialize it using the openConnection() method of the treehouseUrl variable. The openConnection() method returns a URLConnection object, so don't forget to cast it to HttpURLConnection.

 try {
            URL treehouseUrl = new URL(URL);
            HttpURLConnection connection = (HttpURLConnection) treehouseUrl.openConnection();
        }
        catch (MalformedURLException e) {
            Log.e("CodeChallenge", "MalformedURLException caught!", e);
        }
        catch (IOException e) {
          
        }

 

No comments:

Post a Comment