Contoh kode mengirimkan data post dari android ke server PHP dengan menggunakan volley

Berikutnya adalah kode untuk mengirimkan data post dari android ke server PHP  dengan menggunakan volley.

File MainActivity.java

package com.example.basicandroid;

import java.util.HashMap;
import java.util.Map;

import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;

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

public class MainActivity extends Activity {
	Button button;
	String server_url = "http://192.168.1.100/myvolley.php";
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
		button = (Button) findViewById(R.id.b_id_ok);
		button.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
                // TODO Auto-generated method stub
				final RequestQueue requestQueue = Volley.newRequestQueue(MainActivity.this);
				
				StringRequest stringRequest = new StringRequest(Request.Method.POST, server_url, 
				new Response.Listener<String>() {
					@Override
					public void onResponse(String response) {
						Toast.makeText(MainActivity.this, response, Toast.LENGTH_LONG).show();
						requestQueue.stop();
					}		
				}, new Response.ErrorListener() {
					@Override
					public void onErrorResponse(VolleyError error) {
						Toast.makeText(MainActivity.this, "Error ...", Toast.LENGTH_LONG).show();
						error.printStackTrace();
						requestQueue.stop();
					}
				}){
					@Override
					protected Map<String, String> getParams() throws AuthFailureError{
						Map<String, String> params = new HashMap<String, String>();
						params.put("data", "Foo bars");
						return params;
					}
				
				};
				requestQueue.add(stringRequest);
			}
		});
	}

}

File MainActivity.java

<?php
echo $_POST["data"];

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s