Network Presentation

Goals

  • Fetch data from a web page using HTTP

Android Network APIs

Network Communication

  • Requires permission
  • AndroidManifest.xml
    <uses-permission android:name="android.permission.INTERNET" />
    
  • Never execute network requests on the main thread

Asynchronous operations

  • Use the AsyncTask class to execute on separate thread
    new AsyncTask<Void, Void, String>() {
      @Override
      protected String doInBackground(Void... voids) {
          // This runs on a separate thread
          return "Some result of the async operation";
      }
    
      @Override
      protected void onPostExecute(String result) {
        // This runs on main thread
        // result is whatever was returned from doInBackground above
      }
    }.execute();
    

Fetch contents of a web page

  • Create URL object and read contents into String
    URL src = new URL("http://www.mobileapplab.se");
    HttpURLConnection conn = (HttpURLConnection)src.openConnection();
    InputStreamReader input = new InputStreamReader(conn.getInputStream(), "utf-8");
    StringBuilder output = new StringBuilder();
    char[] buffer = new char[4096];
    int len;
    while ((len = input.read(buffer, 0, buffer.length)) > 0) {
        output.append(buffer, 0, len);
    }
    input.close();
    conn.disconnect();
    String result = output.toString();
    

Parsing HTML

  • Jsoup library
    • Slow to parse, but can select elements using jQuery selector syntax
  • String handling
    • Very fast, but fragile and difficult to parse using only string matching
  • Regular expressions
    • Can help with the string handling if source is difficult to match exactly

Parsing HTML using simple string handling

  • Assume HTML has been fetched already
    int found = html.indexOf("currencyRow"); // Find row with CSS class
    while (found >= 0) {
      found = html.indexOf("<span", found); // Find inner SPAN tag
      found = html.indexOf(">", found); // Find end of SPAN tag
      int foundEnd = html.indexOf("<", found); // Find beginning of next tag
      String part = html.substring(found + 1, foundEnd); // Extract relevant text
      found = html.indexOf("currencyRow", found); // Next row
    }
    

Call a web API

  • Structured data using an API
  • No need to parse HTML
  • Documented ways of retrieving and manipulating data
  • REST
    • Definition of how the URL maps to data objects
    • HTTP methods (verbs) for different operations (create, update etc)
  • Data formats
    • XML
    • JSON

JSON

  • Great support in JavaScript
  • Contains
    • Arrays
    • Objects with properties
    • Values
      • Strings
      • Numbers
      • Booleans
  • JSON in text
    [
      { "name": "Adam", "age": 55 }, 
      { "name": "Betty", "age": 28 }
    ]
    

Parsing JSON in Java

  • Parse retrieved text as JSON
    JSONArray items = new JSONArray(data);
    for (int i = 0; i < items.size(); i++) {
      JSONObject item = items.getJSONObject(i);
      String name = item.getString("name");
      int age = item.getInt("age");
    }