Tuesday, July 2, 2013

The Simplest Way to POST Parameters Between Android and PHP (Android SDK)

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
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.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.ByteArrayBuffer;

import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;

public class GetAndPost extends Activity {
 TextView txtvw;
 String text;

 @Override
 public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.main);

  txtvw = (TextView)findViewById(R.id.textview);
  text = "";

  postData();
 }

 public void postData(){  
  // Create a new HttpClient and Post Header
  HttpClient httpclient = new DefaultHttpClient();
  HttpPost httppost = new HttpPost("http://www.yourdomain.com/post.php");  

  try {
   // Add your data
   List nameValuePairs = new ArrayList(1);
   nameValuePairs.add(new BasicNameValuePair("data1", "dataValue"));
   httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));  

   // Execute HTTP Post Request
   HttpResponse response = httpclient.execute(httppost);

   InputStream is = response.getEntity().getContent();
   BufferedInputStream bis = new BufferedInputStream(is);
   ByteArrayBuffer baf = new ByteArrayBuffer(20);

   int current = 0;
      
   while((current = bis.read()) != -1){
    baf.append((byte)current);
   }  

   /* Convert the Bytes read to a String. */
   text = new String(baf.toByteArray());
   txtvw.setText(text);
  } catch (ClientProtocolException e) {
   // TODO Auto-generated catch block
  } catch (IOException e) {
   // TODO Auto-generated catch block
  }
 }
}
On PHP Side
<?php
 if(isset($GLOBALS['HTTP_RAW_POST_DATA']) == TRUE){
  echo $GLOBALS['HTTP_RAW_POST_DATA'];
 }else{
  echo $HTTP_RAW_POST_DATA;
 }
?>

Brand new simple code to deliver JSON POST from Android to PHP:

- Android Code (main.java):
package org.postandget;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;

public class main extends Activity {

 TextView tv;
 String text;

 @Override
 public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.main);

  tv  = (TextView)findViewById(R.id.textview);
  text  = "";

  try {
   postData();
  } catch (JSONException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
 }

 public void postData() throws JSONException{  
  // Create a new HttpClient and Post Header
  HttpClient httpclient = new DefaultHttpClient();
  HttpPost httppost = new HttpPost("http://www.yourdomain.com/post.php");
  JSONObject json = new JSONObject();

  try {
   // JSON data:
   json.put("name", "Fahmi Rahman");
   json.put("position", "sysdev");

   JSONArray postjson=new JSONArray();
   postjson.put(json);

   // Post the data:
   httppost.setHeader("json",json.toString());
   httppost.getParams().setParameter("jsonpost",postjson);

   // Execute HTTP Post Request
   System.out.print(json);
   HttpResponse response = httpclient.execute(httppost);

   // for JSON:
   if(response != null)
   {
    InputStream is = response.getEntity().getContent();

    BufferedReader reader = new BufferedReader(new InputStreamReader(is));
    StringBuilder sb = new StringBuilder();

    String line = null;
    try {
     while ((line = reader.readLine()) != null) {
      sb.append(line + "\n");
     }
    } catch (IOException e) {
     e.printStackTrace();
    } finally {
     try {
      is.close();
     } catch (IOException e) {
      e.printStackTrace();
     }
    }
    text = sb.toString();
   }

   tv.setText(text);

  }catch (ClientProtocolException e) {
   // TODO Auto-generated catch block
  } catch (IOException e) {
      // TODO Auto-generated catch block
     }
 }
}
- Android Layout (main.xml):
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 
 xmlns:android="http://schemas.android.com/apk/res/android"
   android:orientation="vertical"
   android:layout_width="fill_parent"
   android:layout_height="fill_parent">
<ScrollView android:layout_height="wrap_content"
   android:layout_width="match_parent"
   android:id="@+id/scrollView1">
<LinearLayout android:layout_width="match_parent"
   android:id="@+id/linearLayout1"
   android:layout_height="match_parent">
<TextView android:id="@+id/textview"
   android:layout_width="fill_parent"
   android:layout_height="wrap_content"
   android:text="@string/hello" />
</LinearLayout> 
</ScrollView> 
</LinearLayout>
- Android Manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
      package="org.postandget"
      android:versionCode="1"
      android:versionName="1.0">
<application android:icon="@drawable/icon"
             android:label="@string/app_name">
<activity android:name=".main"
          android:label="@string/app_name">
<intent-filter>
      <action android:name="android.intent.action.MAIN" />
      <category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>

<uses-permission android:name="android.permission.INTERNET">
</uses-permission>
</manifest>
- PHP Code:
<?php
 $json = $_SERVER['HTTP_JSON'];
 echo "JSON: \n";
 echo "--------------\n";
 var_dump($json);
 echo "\n\n";

 $data = json_decode($json);
 echo "Array: \n";
 echo "--------------\n";
 var_dump($data);
 echo "\n\n";

 $name = $data->name;
 $pos = $data->position;
 echo "Result: \n";
 echo "--------------\n";
 echo "Name     : ".$name."\n Position : ".$pos; 
?>

No comments:

Post a Comment