Sunday, May 12, 2013

Send Xml Data From Android to PHP server


package com.example.sendxmltest;

import java.io.IOException;

import org.apache.http.HttpEntity;
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.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;

public class MainActivity extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
HttpClient httpclient = new DefaultHttpClient();
   HttpPost httppost = new HttpPost("http://10.0.2.2/server_log/index.php");

   try {
       StringEntity se = new StringEntity( "<aaaLogin inName=\"admin\" inPassword=\"admin123\"/>", HTTP.UTF_8);
       se.setContentType("text/xml");
       httppost.setEntity(se);

       HttpResponse httpresponse = httpclient.execute(httppost);
       HttpEntity resEntity = httpresponse.getEntity();
       Log.e("test",EntityUtils.toString(resEntity));
       //tvData.setText(EntityUtils.toString(resEntity));

   } catch (ClientProtocolException e) {
       // TODO Auto-generated catch block
    Log.e("test",e.getMessage());
       e.printStackTrace();
   } catch (IOException e) {
       // TODO Auto-generated catch block
    Log.e("test",e.getMessage());
    e.printStackTrace();
   }
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}

}


PHP code to receive xml data 

<?php
  /*
   * XML Server.
   */
  // We use php://input to get the raw $_POST results.
  $xml_post = file_get_contents('php://input');
  // If we receive data, save it.
  if ($xml_post) {
    $xml_file = 'received_xml_' . date('Y_m_d-H-i-s') . '.xml';
    $fh       = fopen($xml_file, 'w') or die();
    fwrite($fh, $xml_post);
    fclose($fh);
    // Return, as we don't want to cause a loop by processing the code below.
echo "data xml --".$xml_post;
  }
 // print_r($_SERVER);
  
  return;
?>


No comments:

Post a Comment