Xml/json communication between the Android client and the PHP server

Source: Internet
Author: User
Tags manual php server php website xpath

1.android-Side Send XML request:

There are 2 main points:

	HttpPost HttpPost = new HttpPost (str);
	Httppost.setentity (new Stringentity (XML));

The first is to create a new HttpPost request, initialized with STR, and STR is the server-side interface address

The second article is to create the sending entity, which is initialized with the XML to be sent.

The complete code is as follows (by Buptpatriot):

public class Mobilerss extends activity {String xml= "<?xml version=\" 1.0\ "encoding=\"? gb2312\ Gt;<req name=\ "userlogin\" ><user_id>001</user_id><user_url>\ "http://voice.hupu.com/ Generated/voice/news_nba.xml\ "</user_url><trader_id></trader_id><customer_id></ customer_id><password>123</password><versioninfo>1.0</versioninfo></req></
	Mebs_mobile> ";
	String str= "http://mathandcs.com/MobileRSS/parser.php";
		@Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);
		Setcontentview (R.LAYOUT.ACTIVITY_MOBILE_RSS);
		LOG.D ("Mobile_rss", "Layout Loaded");
		Button Sendbutton = (button) Findviewbyid (R.id.send_button);
					Sendbutton.setonclicklistener (New Onclicklistener () {@Override public void OnClick (view view) {new Thread () {
				           public void Run () {try {httppost httppost = new HttpPost (str); Httppost.setentity (new Stringentity (XML));           
				            HttpResponse HttpResponse = new Defaulthttpclient (). Execute (httppost);
				            LOG.D ("Mobile_rss", "StatusCode:" + httpresponse.getstatusline (). Getstatuscode () + "");
				            String result = entityutils.tostring (httpresponse.getentity ());
				        LOG.D ("Mobile_rss", "Result:" +result);
				        catch (Exception e) {e.printstacktrace ();
			}}.start ();
        
	}
		}); }
}


2.php XML request to handle Android:

First, get the XML from Android ():

At first I thought using PHP $_post[to get, but not successful, find the following workaround: (Reference: http://taoshi.blog.51cto.com/1724747/1165499)

$xmldata = file_get_contents ("Php://input"); 
$data = (array) simplexml_load_string ($xmldata); 
Print_r ($data);

Note:

1), php://input data is always the same as $http_raw_post_data, but php://input more effective than $http_raw_post_data, and do not need special settings php.ini

2), only when Content-type is application/x-www-data-urlencoded, php://input data is consistent with $_post data.


Then, get the XML content through the Http_get_contents method

Finally, with the help of PHP DOM operation, XML file parsing is realized:

Reference PHP website Manual:

1), http://cn2.php.net/manual/zh/class.domdocument.php

2), http://www.w3schools.com/dom/dom_node.asp

3), http://www.cnblogs.com/meteoric_cry/archive/2011/04/07/2007628.html

Node Object Properties

Property
Description
BaseURI Returns the absolute base URI of a node
ChildNodes Returns a nodelist of nodes for a node
FirstChild Returns the "a" node
LastChild Returns the last child of a node
LocalName Returns The local part of the name of node
NamespaceURI Returns the namespace URI of a node
NextSibling Returns the node immediately following a node
NodeName Returns the name of a node, depending on its type
NodeType Returns the type of a node
NodeValue Sets or returns the value of a node, depending on its type
Ownerdocument Returns the root element (document object) for a node
ParentNode Returns The parent node of a node
Prefix Sets or returns the namespace prefix of a node
PreviousSibling Returns the node immediately before a node
Textcontent Sets or returns the textual content of a node and its descendants


The complete code is as follows (by Wusuopubupt):

<?php $xmldata = file_get_contents ("Php://input"); 
$data = (array) simplexml_load_string ($xmldata);

Print_r ($data); $url = "Http://voice.hupu.com/generated/voice/news_nba.xml";

Hupu XML $xmlfile = file_get_contents ($url);
$dom = new DOMDocument ();
$dom->loadxml ($xmlfile);
$xpath = new Domxpath ($dom);
$query = "//i";
$entries = $xpath->query ($query);

$dom->savexml ();
$items = $dom->getelementsbytagname ("item");
$item = $items->item (0); 
Var_dump ($item->nodevalue);
$index = 0;
$len = $items->length;

$content = Array ();
	while ($index < $len) {$nodeItem = $items->item ($index);
	$titles = $nodeItem->getelementsbytagname ("title");
	$links = $nodeItem-> getelementsbytagname ("link");
	$descriptions = $nodeItem-> getElementsByTagName ("description");
	foreach ($titles as $title) {$content [$index] [' title '] = $title->nodevalue;
	foreach ($links as $link) {$content [$index] [' link '] = $link->nodevalue; foreach ($descriptions as $Description) {$content [$index] [' description '] = $description->nodevalue;
} $index + +;
Header ("Content-type:application/json");

echo Json_encode ($content);
/* $content = array ();
		for ($i = 0; $i < $len; $i + +) {foreach ($items->item ($i)->getelementsbytagname (' title ') as $title) {
		Var_dump ($title);
	$content [$i] [' title '] [] = $title->nodevalue;

}*///var_dump ($content);
	function Http_get ($url, $ref _url=null) {$ch = Curl_init ();
	curl_setopt ($ch, Curlopt_url, $url);
	curl_setopt ($ch, Curlopt_returntransfer, 1); curl_setopt ($ch, Curlopt_useragent, "mozilla/5.0" (Windows NT 6.1;
	WOW64) applewebkit/537.36 (khtml, like Gecko) chrome/27.0.1453.81 safari/537.36 ");
	if ($ref _url) {curl_setopt ($ch, Curlopt_referer, $ref _url);
	curl_setopt ($ch, Curlopt_connecttimeout, 3);
	curl_setopt ($ch, Curlopt_timeout, 3);
	$data = curl_exec ($ch);
	Curl_close ();
return $data;
 }?>


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.