Laman

Android Mengirim Data ke Server PHP dengan Http POST dan AsyncTask

    Pada Android OS versi 2.2-2.3 mungkin menggunakan http post biasa sudah bisa mengirim data dengan proses yang berat dan kadang membuat hp membeku/berhenti bekerja sampai data yang di minta di dapatkan. Namun pada Android OS versi 4.0 ke atas, proses mengirim data menggunakan http post yang berat tersebut jika menggunakan script yang di gunakan pada Android OS versi 2.3 script tersebut tidak akan berjalan walaupun permission internet yang ada manifiest sudah di tambah tetap data tidak akan terkirim, saya sempat pusing di buatnya, cari-cari di internet selama dua hari akhirnya pikiran saya terbuka dan ternyata OS versi 4.0 ke atas proses http di pindah ke background proses, dan salah satu caranya menggunakan AsyncTask. Contoh sederhana pengiriman ke server yang saya buat yaitu login melalui hp Android, mengirimkan data username dan password kemudian di balas oleh server.

Buat sebuah file PHP dan taruh di localhost anda save dengan nama login.php
<?php
$user=$_POST['username'];
$pass=$_POST['password'];
if($user == "admin" && $pass=="admin"){
   echo "Login Sukses";
}else{
   echo "Login Gagal";
}
?>



Dari hp Android akan mengirimkan data ke server php diterima file login.php dan akan mencocokkan apakah data yang diterima adalah username=admin dan password=admin, jika benar maka keluar tulisan "Login Sukses" jika salah maka keluar tulisan "Login Gagal".

Berikut script pada aplikasi Android.
activity_main.xml


 
 
 
 
 
 



MainActivity.java

package com.httpasynctask;

import java.util.ArrayList;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;

import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

public class MainActivity extends Activity {

 Button loginBtn;
 EditText user, pass, status;
 //alamat server
 private String url = "http://192.168.1.105/login.php";

 /** Called when the activity is first created. */
 @Override
 public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);

  user = (EditText) findViewById(R.id.userInput);
  pass = (EditText) findViewById(R.id.passInput);
  status = (EditText) findViewById(R.id.status);
  loginBtn = (Button) findViewById(R.id.button1);
 }

 public void onClickLogin(View v) {
  // TODO Auto-generated method stub
  String uname = user.getText().toString();
  String pwd = pass.getText().toString();
  sendData task = new sendData();
  task.execute(new String[]{uname, pwd});
 }
 
 private class sendData extends AsyncTask {
  @Override
  protected String doInBackground(String... params) {
   // TODO Auto-generated method stub
   ArrayList postParameters = new ArrayList();
   postParameters.add(new BasicNameValuePair("username", params[0] ));
   postParameters.add(new BasicNameValuePair("password", params[1] ));
   String res = null;
   try {
      String response = CustomHttpClient.executeHttpPost(url, postParameters);
      res=response.toString();
      res=res.trim();
      //res= res.replaceAll("\\s+","");                        
   }catch (Exception e) {
      status.setText(e.toString());
   }
   return res;
  }//close doInBackground
  
  @Override
  protected void onPostExecute(String result) {
   //result data send
   status.setText(result);
  }//close onPostExecute
  
 }// close validateUserTask 
}

CustomHttpClient.java

package com.httpasynctask;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URI;
import java.util.ArrayList;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
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.conn.params.ConnManagerParams;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;

public class CustomHttpClient {
/** The time it takes for our client to timeout */
    public static final int HTTP_TIMEOUT = 30 * 1000; // milliseconds

    /** Single instance of our HttpClient */
    private static HttpClient mHttpClient;

    /**
     * Get our single instance of our HttpClient object
     * @return an HttpClient object with connection parameters set
     */
    private static HttpClient getHttpClient() {
        if (mHttpClient == null) {
            mHttpClient = new DefaultHttpClient();
            final HttpParams params = mHttpClient.getParams();
            HttpConnectionParams.setConnectionTimeout(params, HTTP_TIMEOUT);
            HttpConnectionParams.setSoTimeout(params, HTTP_TIMEOUT);
            ConnManagerParams.setTimeout(params, HTTP_TIMEOUT);
        }
        return mHttpClient;
    }
    /**
     * Performs an HTTP Post request to the specified url with the
     * specified parameters.
     * @param url The web address to post the request to
     * @param postParameters The parameters to send via the request
     * @return The result of the request
     * @throws Exception
     */
    public static String executeHttpPost(String url, ArrayList postParameters) throws Exception {
        BufferedReader in = null;
        try {
            HttpClient client = getHttpClient();
            HttpPost request = new HttpPost(url);
            UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(postParameters);
            request.setEntity(formEntity);
            HttpResponse response = client.execute(request);
            in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));

            StringBuffer sb = new StringBuffer("");
            String line = "";
            String NL = System.getProperty("line.separator");
            while ((line = in.readLine()) != null) {
                sb.append(line + NL);
            }
            in.close();

            String result = sb.toString();
            return result;
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * Performs an HTTP GET request to the specified url.
     *
     * @param url The web address to post the request to
     * @return The result of the request
     * @throws Exception
     */
    public static String executeHttpGet(String url) throws Exception {
        BufferedReader in = null;
        try {
            HttpClient client = getHttpClient();
            HttpGet request = new HttpGet();
            request.setURI(new URI(url));
            HttpResponse response = client.execute(request);
            in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));

            StringBuffer sb = new StringBuffer("");
            String line = "";
            String NL = System.getProperty("line.separator");
            while ((line = in.readLine()) != null) {
                sb.append(line + NL);
            }
            in.close();

            String result = sb.toString();
            return result;
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

Download source code Android login dengan PHP di Dropbox
Semoga bermanfaat.

No comments:

Post a Comment

Silahkan