Kamis, 23 Juni 2011

Android: Pengiriman Data GET/POST Pada Koneksi HTTP

Koneksi HTTP merupakan salah satu fitur yang diusung Android. Dengan fitur ini, aplikasi berbasis Android dapat terkoneksi ke server (internet) untuk saling ‘ngobrol’. Koneksi HTTP memiliki 2 macam metode request, GET dan POST.
GET adalah metode pada koneksi HTTP yang menyertakan parameter pada URI yang dituju. Sedangkan metode POST, parameter bukan menjadi bagian dari URI, melainkan berupa data yang dikirimkan pada message body request. Untuk lebih jelasnya mengenai kedua metode HTTP ini, silahkan baca disini.
Pada artikel teknologi informasi berikut, saya akan mencoba mengupas lebih lanjut mengenai penggunaan koneksi HTTP di lingkungan Android. Mungkin Anda sudah membaca beberapa artikel mengenai Android sebelumnya. Dengan membaca artikel ini, harapannya Anda akan lebih mengerti bagaimana cara melakukan pengiriman data ke server menggunakan protokol HTTP.
3 kelas yang akan digunakan untuk koneksi adalah HttpClient, HttpPost, dan HttpGet. Coba Anda perhatikan kelas HttpRequest.java berikut. Kelas ini berfungsi untuk melakukan pengiriman data ke Web server.
package com.secangkirkopipanas.android.apps;
 
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
 
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
 
import android.util.Log;
 
/**
 * This class is used for sending data to the server
 *
 * @author Robertus Lilik Haryanto
 * @version 1.0
 */
public class HttpRequest {
 
    private HttpResponse response = null;
 
    private String url = null;
    private Map<String, String> params = new HashMap<String, String>();
    private Method requestMethod = null;
 
    enum Method {
        GET, POST
    }
 
    public HttpRequest(String url, Map<String, String> params, Method requestMethod) {
        this.url = url;
        this.params = params;
        this.requestMethod = requestMethod;
    }
 
    public String sendRequest() {
 
        Log.d("HttpRequest@sendRequest", "Starting request...");
 
        Log.d("HttpRequest@sendRequest", "URL: " + this.url + ", requestMethod: "
                + this.requestMethod);
 
        // Create a new HttpClient and Post Header
        HttpClient httpClient = new DefaultHttpClient();
        HttpRequestBase httpRequest = null;
 
        InputStream responseStream = null;
        String responseString = null;
 
        try {
            if (this.requestMethod == Method.POST) {
                httpRequest = new HttpPost(this.url);
 
                if (httpRequest != null) {
                    ((HttpPost) httpRequest).setEntity(new UrlEncodedFormEntity(
                            encodePostParameter(this.params)));
                    // Execute HTTP Post Request
                    response = httpClient.execute(httpRequest);
                }
 
            } else if (this.requestMethod == Method.GET) {
                httpRequest = new HttpGet(this.url + encodeGetParameter(this.params));
 
                if (httpRequest != null) {
                    // Execute HTTP Post Request
                    response = httpClient.execute(httpRequest);
                }
            }
 
            if (response != null) {
                responseStream = response.getEntity().getContent();
                responseString = generateResponseString(responseStream);
            }
 
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
 
        Log.d("HttpRequest@sendRequest", "Finished!");
 
        return responseString;
    }
 
    public List<BasicNameValuePair> encodePostParameter(Map<String, String> params) {
        List<BasicNameValuePair> nameValuePairs = new ArrayList<BasicNameValuePair>(1);
        Set<String> keys = params.keySet();
        for (String key : keys) {
            String value = params.get(key);
            nameValuePairs.add(new BasicNameValuePair(key, value));
        }
        return nameValuePairs;
    }
 
    public String encodeGetParameter(Map<String, String> params) {
        StringBuilder buff = new StringBuilder("?");
        Set<String> keys = params.keySet();
        for (String key : keys) {
            String value = params.get(key);
            buff.append(key).append("=").append(URLEncoder.encode(value));
        }
        return buff.toString();
    }
 
    public String generateResponseString(InputStream stream) {
        InputStreamReader reader = new InputStreamReader(stream);
        BufferedReader buffer = new BufferedReader(reader);
        StringBuilder sb = new StringBuilder();
 
        try {
            String cur;
            while ((cur = buffer.readLine()) != null) {
                sb.append(cur + "\n");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
 
        try {
            stream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return sb.toString();
    }
}
Berikut adalah layout (main.xml) yang digunakan pada aplikasi ini:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout android:id="@+id/mainLayout"
    android:orientation="vertical" android:layout_width="fill_parent"
    android:layout_height="fill_parent" xmlns:android="http://schemas.android.com/apk/res/android">
    <TextView android:id="@+id/lblName" android:layout_width="fill_parent"
        android:layout_height="wrap_content" android:text="Your Name:">
    </TextView>
    <EditText android:id="@+id/txtName" android:layout_width="fill_parent"
        android:singleLine="true" android:layout_height="wrap_content"
        android:cursorVisible="true" android:inputType="text">
    </EditText>
    <Button android:id="@+id/btnSubmit" android:layout_width="fill_parent"
        android:layout_height="wrap_content" android:text="Submit">
    </Button>
    <Button android:id="@+id/btnReset" android:layout_width="fill_parent"
        android:layout_height="wrap_content" android:text="Reset">
    </Button>
</LinearLayout>
Berikut adalah kode program untuk menu (menu.xml):
    <item android:id="@+id/quit"
          android:title="Quit" />
</menu>
Berikut cara penggunaan kelas HttpRequest.java yang sudah Anda buat sebelumnya:
...
HttpRequest req = new HttpRequest(HTTP_URL, params, HttpRequest.Method.POST);
String response = req.sendRequest();
...
Berikut adalah kode program lengkap untuk wrapper Android (MyAndroidApps.java).
package com.secangkirkopipanas.android.apps;
 
import java.util.HashMap;
import java.util.Map;
 
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
 
/**
 * This class is a wrapper of Android to send request to the Web server
 *
 * @author Robertus Lilik Haryanto
 * @version 1.0
 */
public class MyAndroidApps extends Activity {
 
    private final String HTTP_URL = "http://192.168.0.108/android/hello.php";
 
    private final int MENU_QUIT = 0;
 
    private Button btnSubmit = null;
    private Button btnReset = null;
    private EditText txtName = null;
 
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
 
        // setting the view to our newly created layout
        setContentView(R.layout.main);
 
        txtName = (EditText) findViewById(R.id.txtName);
 
        // initializing button, including layout parameters
        btnSubmit = (Button) findViewById(R.id.btnSubmit);
        btnSubmit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                sayHello();
            }
 
        });
 
        btnReset = (Button) findViewById(R.id.btnReset);
        btnReset.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                txtName.setText("");
            }
 
        });
    }
 
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        menu.add(0, MENU_QUIT, 0, "Quit");
        return true;
 
    }
 
    /* Handles item selections */
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case MENU_QUIT:
                quit();
                return true;
        }
        return false;
    }
 
    public void sayHello() {
        AlertDialog alertDialog = new AlertDialog.Builder(this).create();
        alertDialog.setTitle("Sending Request");
        alertDialog.setMessage("This process will take few seconds. Are you sure want to submit?");
        final String name = txtName.getText().toString();
        alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                Map<String, String> params = new HashMap<String, String>();
                params.put("name", name);
                Log.i("sayHello@name", name);
 
                Toast.makeText(MyAndroidApps.this, "Sending request, please wait...",
                        Toast.LENGTH_SHORT).show();
                HttpRequest req = new HttpRequest(HTTP_URL, params, HttpRequest.Method.POST);
                String response = req.sendRequest();
                Log.i("sayHello@response", response);
 
                Toast.makeText(MyAndroidApps.this, response, Toast.LENGTH_LONG).show();
            }
        });
        alertDialog.setIcon(R.drawable.icon);
        alertDialog.show();
    }
 
    public void quit() {
        AlertDialog alertDialog = new AlertDialog.Builder(this).create();
        alertDialog.setTitle("Quit");
        alertDialog.setMessage("Are you sure?");
        alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                finish();
            }
        });
        alertDialog.setIcon(R.drawable.icon);
        alertDialog.show();
    }
}
Jika Anda sudah selesai membuat kode program di atas, sekarang adalah saatnya Anda membuat aplikasi di Web server. Kali ini saya akan membuatnya menggunakan PHP. Coba simak kode berikut (hello.php):
...
$name = trim($_POST["name"]);
echo "Hello, " . $name . "! This is response from server.";
...
Simpan dan lakukan kompilasi terhadap kode program di atas, kemudian jalankan. Anda akan mendapatkan tampilan seperti gambar di bawah ini:
Halaman Utama
Halaman Utama
Halaman Konfirmasi
Halaman Konfirmasi
Informasi Pengiriman






http://secangkirkopipanas.com

Tidak ada komentar:

Posting Komentar