Pemrograman Mobile

Lanjut

#4: Akses Internet

Muhamad Saad Nurul Ishlah, M.Comp.

 

Program Studi Sistem Informasi, Sekolah Vokasi,

Universitas Pakuan

Pembahasan

  • Perizinan
  • Mengatur koneksi jaringan
  • Worker thread
  • Membuat URI
  • Koneksi klien HTTP
  • Pustaka koneksi klien HTTP
  • Mengubah respon ke String
  • Memparsing hasil

Terkoneksi ke Internet

Langkah Terhubung ke Internet

  • Tambah perizinan ke Android Manifest

  • Cek koneksi jaringan

  • Buat thread pekerja (worker thread)

  • Implementasi background task

    • Buat URI

    • Buat koneksi HTTP

    • Hubungkan dan Ambil Data

  • Proses hasil

    • Parsing hasil

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

// Izin cek status jaringan
<uses-permission    
    android:name="android.permission.ACCESS_NETWORK_STATE"/>

---

// Cek koneksi jaringan
ConnectivityManager connMgr = 
		(ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);

NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();

if (networkInfo != null && networkInfo.isConnected()) {
    // Create background thread to connect and get data
    new DownloadWebpageTask().execute(stringUrl);
} else {
    textView.setText("No network connection available.");
}

---

// Cek jaringan WiFi dan Mobile
NetworkInfo networkInfo = 
    connMgr.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
boolean isWifiConn = networkInfo.isConnected();

networkInfo = 
    connMgr.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
boolean isMobileConn = networkInfo.isConnected();

---

// Gunakan worker thread
AsyncTask 		   : kerjaan yang sangat pendek, atau tidak ada hasil yang dikembalikan ke UI
AsyncTaskLoader    : untuk kerjaan yang lebih panjang, atau yang mengambalikan ke UI
Background Service : pembahasan lain

---

Dalam background task (contoh di doInBackground())
1. Buat URI
2. Buat koneksi HTTP
3. Unduh Data

---

/* 1. Buat URI untuk request
 * 	  contoh API URL: https://www.googleapis.com/books/v1/volumes?q=pride+prejudice&maxResults=5&printType=books
 */

final String BASE_URL = 
	"https://www.googleapis.com/books/v1/volumes?";    
final String QUERY_PARAM = "q"; 
final String MAX_RESULTS = "maxResults"; 
final String PRINT_TYPE = "printType";
Uri builtURI = Uri.parse(BASE_URL).buildUpon()
       .appendQueryParameter(QUERY_PARAM, "pride+prejudice")
       .appendQueryParameter(MAX_RESULTS, "10")
       .appendQueryParameter(PRINT_TYPE, "books")
       .build();
URL requestURL = new URL(builtURI.toString());


/* 2. Buat koneksi HTTP dan dapatkan respon
 * 
 * Buat koneksi dari nol (from scratch)
 * - GUnakan HttpURLConnection
 * - Harus dilakukan di thread yang terpisah
 * - Membutuhkan InputStreams dan blok try/catch
 *
 */

HttpURLConnection conn = 
		(HttpURLConnection) requestURL.openConnection();

try {
	// Konfigurasi koneksi
    conn.setReadTimeout(10000 /* milliseconds */);
    conn.setConnectTimeout(15000 /* milliseconds */);
    conn.setRequestMethod("GET");
    conn.setDoInput(true);

    // 3. Hubungkan dan dapatkan respon
    conn.connect();
    int response = conn.getResponseCode();

    InputStream is = conn.getInputStream();
    String contentAsString = convertIsToString(is, len);

	return contentAsString;
} finally {
	conn.disconnect();
	if (is != null) {
		is.close();
	}
}

---

/*
 * Konversi stream input menjadi string
 */
public String convertIsToString(InputStream stream, int len) 
    throws IOException, UnsupportedEncodingException {
    
    Reader reader = null;
    reader = new InputStreamReader(stream, "UTF-8");
    char[] buffer = new char[len];
    reader.read(buffer);
    return new String(buffer);
}

// Gunakan BufferedReader agar lebih efisien
StringBuilder builder = new StringBuilder();
BufferedReader reader = 
	new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine()) != null) {
   builder.append(line + "\n");
}
if (builder.length() == 0) {
   return null;
}
resultString = builder.toString();

Parsing hasil request

  • Implementasikan metode untuk menerima dan menghandel hasil (onPostExecute())
  • Respon biasanya dalam bentuk JSON atau XML

 

Parsing hasil menggunakan kelas-kelas pembantu

Contoh Parsing JSON

{
  "population": 1252000000,
  "country": "India",
  "cities": [
    "New Delhi", 
    "Mumbai", 
    "Kolkata", 
    "Chennai"
  ]
}
JSONObject jsonObject = new JSONObject(response);
String nameOfCountry = (String) jsonObject.get("country");  
long population = (Long) jsonObject.get("population");  
JSONArray listOfCities = (JSONArray) jsonObject.get("cities"); 
Iterator<String> iterator = listOfCities.iterator();  

while (iterator.hasNext()) {  
    // do something  
}  

JSON

Java

Contoh Parsing JSON 2

{
  "menu": {
    "id": "file",
    "value": "File",
    "popup": {
      "menuitem": [
        {"value": "New", "onclick": "CreateNewDoc()"},
        {"value": "Open", "onclick": "OpenDoc()"},
        {"value": "Close", "onclick": "CloseDoc()"}
      ]
    }
  }
}
// Get "onclick" value of the 3rd item in the "menuitem" array

JSONObject data = new JSONObject(responseString);
JSONArray menuItemArray = 
	data.getJSONArray("menuitem");
JSONObject thirdItem =
	menuItemArray.getJSONObject(2);

String onClick = thirdItem.getString("onclick");

JSON

Java

HTTP Client Connection Libraries

Pustaka Koneksi Klien HTTP

Melakukan koneksi menggunakan Pustaka

  • Gunakan pustaka luar seperti OkHttp atau Volley

  • Dapat dipanggil pada thread utama (main thread)

  • Kode lebih sedikit

 

Volley

RequestQueue queue = Volley.newRequestQueue(this);
String url ="http://www.google.com";

StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
            new Response.Listener<String>() {
    @Override
    public void onResponse(String response) {
        // Do something with response
    }
}, new Response.ErrorListener() {
    @Override
    public void onErrorResponse(VolleyError error) {}
});
queue.add(stringRequest);

OkHttp

OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
    .url("http://publicobject.com/helloworld.txt").build();
client.newCall(request).enqueue(new Callback() {
    @Override
    public void onResponse(Call call, final Response response) 
        throws IOException {  
        try {
            String responseData = response.body().string();
            JSONObject json = new JSONObject(responseData);
            final String owner = json.getString("name");
        } catch (JSONException e) {}
    }
});

Adakah pustaka lainnya?

Silahkan diskusikan di forum di e-learning

Pelajari Lebih Lanjut

Sumber untuk Dipelajari

Referensi

Referensi

  • Diterjemahkan dari slide Android Developer Fundamentasl V2: Internet Connection

Terima Kasih

PML4: Akses Internet

By M. Saad Nurul Ishlah

PML4: Akses Internet

  • 293