android客户端同php服务端进行XML/JSON通信
1.android端发送XML请求:
主要有2点:
HttpPost httpPost = new HttpPost(str);httpPost.setEntity(new StringEntity(xml));
第一条是创建新的HTTPPost请求,用str初始化,str是服务端接口地址
第二条是创建发送实体,用待发送的xml初始化
完整代码如下(by buptpatriot):
public class MobileRSS extends Activity {String xml="<?xml version=\"1.0\" encoding=\"GB2312\"?><MEBS_MOBILE><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";@Overrideprotected 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() {@Overridepublic 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处理android的XML请求:
首先,获得android传过来的XML():
开始我以为用php的$_POST[ ]来取得,但是不成功,找到下面的解决方法:(参考: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数据总是跟$HTTP_RAW_POST_DATA相同,但是php://input比$HTTP_RAW_POST_DATA更凑效,且不需要特殊设置php.ini
2)、只有Content-Type为application/x-www-data-urlencoded时,php://input数据才跟$_POST数据相一致。
然后,通过http_get_contents方法获取xml内容
最后借助php的DOM操作,实现对XML文件的解析:
参考php官网手册:
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 child nodes for a node |
firstChild | Returns the first child of a node |
lastChild | Returns the last child of a node |
localName | Returns the local part of the name of a 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 |
完整代码如下(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;
}
?>
android客户端同php服务端进行XML/JSON通信相关推荐
- 解决android客户端上传图片到服务端时,图片损坏的问题
解决android客户端上传图片到服务端时,图片损坏的问题 参考文章: (1)解决android客户端上传图片到服务端时,图片损坏的问题 (2)https://www.cnblogs.com/cnbl ...
- 视频列表的android客户端和springmvc服务端实现(三)
项目运行图太大了,我放在github上了 https://github.com/1181631922/Recreation/blob/master/readme/video/videos2.gif 服 ...
- Android客户端与PHP服务端API接口Token安全验证
Android客户端: 1.写一个生成token的算法 /*** 生成api接口的token* @param map* @param apikey* @return*/public static St ...
- c pc 和android通讯,Android 客户端与PC服务端socket通信接收与发送图片(终结者)
前言 这个解决方案是我和队友在<物联网>比赛的集训中得到的.在socket中Android客户端接收图片是相当的棘手(反正我当时就是这样觉得),接收文字还算简单.在刚开始接触socket接 ...
- android java websocket client_websocket服务端,android客户端示例
服务端库依赖详见章末 #####spring websocket服务端代码(会话过程) public class HandshakeInterceptor extends HttpSessionHan ...
- grpc 客户端的context 服务端获取不到_MLamp;DEV[10] | gRPC的应用
上一期和大家谈到了gRPC的快速开始,我么哪知道了gRPC是什么以及怎么快速启动,那么现在,我们来看看这个玩意具体内部是怎么运作的,这里我们同样以helloworld这个为例子来去谈.首先上期内容在这 ...
- http 缓存分为客户端缓存和服务端缓存
http 缓存分为客户端缓存和服务端缓存 1. 客户端缓存 客户端缓存指的是浏览器缓存, 浏览器缓存是最快的缓存, 因为它直接从本地获取(但有可能需要发送一个请求), 它的优势是可以减少网络流量, 加 ...
- 服务器客户端通信协议,Redis服务端-客户端通信协议
了解Redis通信内容 Redis我们都比较熟悉,可以用来做缓存.分布式锁等,但是,其中的客户端与服务端是如何进行通信的呢? 我们可以分别模拟一个服务端或者客户端,打印查看来自实际连接的请求来获取它们 ...
- Unity中进行网络通信:三:unity客户端和Unity服务端互相发消息
目录 一.目的 1.想知道:Unity中进行网络通信:unity客户端和Unity服务端互相发消息 二.参考 1.unity3D中使用Socket进行数据通信(三) 三.操作:一:完成:在同一个Uni ...
- 附件统一处理starter,含附件客户端和附件服务端
文章目录 附件统一处理starter,可分别作为附件客户端和附件服务端使用 一 关于项目中附件的概述 二 概要描述 三 附件starter功能划分 3.1 附件服务器,真实的存储附件 3.1.1 为前 ...
最新文章
- SpringBoot中Tomcat配置(学习SpringBoot实战)
- oracle 计算中位数,SQL 如何计算每个分组的中位数
- bs4 乱码_Python BeautifulSoup中文乱码问题的2种解决方法
- asp activex 读取服务器上的文件,webshell中上传asp文件调用服务器ActiveX控件溢出获取shell...
- 3842开关电源完整原理图_8大常见开关电源电路分析,让你项目设计更轻松!
- 专栏全年主题合辑-代码中文命名相关实践 2018-11-10
- python怎么设置为中文-python设置中文界面实例方法
- 传感器i2c与arduino连接_ARDUINO的I2C通信详解 - arduino读取I2C总线上连接设备的地址...
- 【搞个事】主页被劫持,改注册表进行修复
- 裸辞之后自己在家接单是什么体验?
- 数字系统设计, 8个经典计数器电路方案合辑
- 【Android多线程】哲学家就餐问题
- android课程表
- 关于gvim的高级应用
- 必看:C语言高效学习方法(附经典试题详解)
- python匿名函数里用for_Python基础之(内置函数、匿名函数、递归)
- 可以模拟人工操作的软件;如访问网页,在网页中自动获取固定信息等
- 计算机缩写术语完全介绍 By 001pc @ 1997.10.1-2004-6-12
- 网站导航:如何在线生成自定义的二维码?(要美观不要俗气)
- z77用m2固态_Z77也能用M.2固态
热门文章
- 好用的软件及网站收录
- 80004005错误代码_WIN7错误代码0×80004005图文解决教程
- QQ空间优化让百度收录你
- caffe安装出现 “error : too few arguments in function call” 的错误
- cmd脚本实现自动拨号
- 【Linux服务器架设】搭建存储服务器-NFS
- SMT32的RTC的晶振为什么是32768Hz
- VS2013新建项目出现脚本错误的解决办法
- 2021瑞安高考成绩查询,2021年瑞安高考状元名单公布,瑞安文理科状元是谁多少分...
- WPF应用无法使用Snoop分析的解决办法