INTRODUCTION TO ANDROID MOBILE APP DEVELOPMENT MUHAMMAD BAGIR., MTI
CONTENTS • Konsep Android Client Server
• Implementasi Aplikasi Android Client-Server dengan Socket Connection • Implementasi Aplikasi Android Client Server dengan Web Service (JSON)
• HTTPRequest • HTTPResponse • Java Streaming
• Posting Input Data • Contoh dengan Login Activity
CLIENT - SERVER •
Client mempunyai kemampuan untuk melakukan proses sendiri. Ketika sebuah client meminta suatu data ke server, server akan segera menanggapinya dengan memberikan data yang diminta ke client yang bersangkutan. Setelah data diterima, client segera melakukan pemrosesan.
Definisi Client dan Server: •
Client – Web browser/Aplikasi yang memampukan pengguna (user) untuk melakukan akses secara remote/jarak jauh
•
Server - Suatu unit komputer yang secara konstan menjalankan program dan menyediakan informasi ke web.
Cara Implementasi Aplikasi Android berbasis Client - Server :
1. Implementasi menggunakan Socket Connection 2. Implementasi menggunakan Web Service
MEMBUAT SERVER SOCKET CONNECTION •
Membuat Koneksi
serverSocket = new ServerSocket(port); •
Menerima Koneksi
while (true) { clientSocket = serverSocket.accept(); inputStreamReader = new InputStreamReader(clientSocket.getInputStream()); bufferedReader = new BufferedReader(inputStreamReader); //get the client message message = bufferedReader.readLine();
System.out.println(message); inputStreamReader.close(); clientSocket.close();
MEMBUAT ANDROID CLIENT •
Membuat koneksi ke Server dan mengirimkan message
private Socket client; private PrintWriter printwriter; client = new Socket("10.0.2.2", 1234); //connect to server printwriter = new PrintWriter(client.getOutputStream(),true);
printwriter.write(message); printwriter.write("testing"); printwriter.flush(); printwriter.close(); client.close(); //closing the connection
Http Request Making HTTP GET Request HttpClient httpClient = new DefaultHttpClient(); HttpGet httpGet = new HttpGet(“url String here”);
HttpResponse httpResponse = httpClient.execute(httpGet); HttpEntity entity = httpResponse.getEntity(); InputStream is = entity.getContent();
InputStream contain data we retrieve from the request, we can change it accordingly to the response we got from server e.q. String or Bitmap image
IMPLEMENTASI DENGAN WEB SERVICE •
Buat File PHP dengan GET dan proses input ke DB
•
Lalu Buat Aplikasi Android yang mengirimkan request posting ke server dan menampilkan response sukses jika data telah diterima server:
HttpClient client = new DefaultHttpClient(); HttpGet request = new HttpGet(URL); •
Menerima dan Menampilkan hasil response
HttpResponse response = client.execute(request); txtResult.setText(request(response));
MEMBUAT REQUEST private static String requested(HttpResponse response){
String result = ""; ……….. InputStream in = response.getEntity().getContent(); BufferedReader reader = new BufferedReader(new InputStreamReader(in));
StringBuilder str = new StringBuilder(); String line = null; while ((line = reader.readLine()) != null) { }
in.close(); result = str.toString();
str.append(line+"n");
MEMPROSES RESPONSE DARI STRING REQUEST private void getRequest(EditText txtResult, String URL) { Log.d("getRequest", URL); HttpClient client = new DefaultHttpClient(); HttpGet request = new HttpGet(URL); try { HttpResponse response = client.execute(request); txtResult.setText(requested(response)); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) {
e.printStackTrace(); }
}
URL REQUEST • Untuk meneruskan data ke server, URL Request harus ditentukan dengan ketentuan : http://server:port/aplikasi/file.php?parameter=value • Panggil metode dengan url yang sudah ditentukan
getRequest(myEditText, url);
Http Request(cont..) Making HTTP POSTRequest HttpClient httpClient = new DefaultHttpClient(); HttpGet httpPost = new HttpPost(“url String here”);
List
params = new ArrayList(2); params.add(new BasicNameValuePair(”param1", ”value")); params.add(new BasicNameValuePair(”param2", “value”)); httpPost.setEntity(new UrlEncodedFormEntity(params); HttpResponse httpResponse = httpClient.execute(httpPost); HttpEntity entity = httpResponse.getEntity(); InputStream is = entity.getContent();
Reading a String Response String line = null; StringBuilder total = new StringBuilder();
// Wrap a BufferedReader around the InputStream BufferedReader rd = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8); // Read response until the end while ((line = rd.readLine()) != null) { total.append(line+"\n"); } String responseString = total.toString();
LOGIN ACTIVITY DENGAN POST •
Membuat Paramater dan memberikan value ke pArameter parameter = new ArrayList(2); parameter.add(new BasicNameValuePair("user",usr.trim()));
parameter.add(new BasicNameValuePair("password",pass.trim())); •
Metode koneksi dan mengirimkan Parameter httpclient = new DefaultHttpClient(); httppost = new HttpPost("http://10.0.2.2:80/contoh_koneksi/login.php"); httppost.setEntity(new UrlEncodedFormEntity(parameter)); httprespon = httpclient.execute(httppost); is = httprespon.getEntity().getContent(); int pj=(int)httprespon.getEntity().getContentLength(); data = new byte[pj];
buffer = new StringBuffer(); int len = 0; while (-1 != (len = is.read(data))) { buffer.append(new String(data,0,len)); } is.close();
MEMERIKSA NILAI BALIK DARI SERVER if(buffer.charAt(0)=='Y') { Toast.makeText(this, "Login Sukses...", Toast.LENGTH_LONG).show(); Intent myIntent = new Intent (this,ContohAja.class); startActivity(myIntent); // ContohAja.session=userText.getText().toString(); } else { Toast.makeText(this, "Invalid User atau Password...", Toast.LENGTH_LONG).show(); }