某些情况下我们可能需要与Mysql或者Oracle数据库进行数据交互

有些朋友的第一反应就是直接在Android中加载驱动然后进行数据的增删改查。我个人不推荐这种做法,一是手机毕竟不是电脑,操作大量数据费时费电;二是流量贵如金那。我个人比较推荐的做法是使用Java或PHP等开发接口或者编写WebService进行数据库的增删该查,然后Android调用接口或者WebService进行数据的交互。本文就给大家讲解在Android中如何调用远程服务器端提供的WebService。
既然是调用WebService,我们首先的搭建WebService服务器。为了便于操作,我们就使用网上免费的WebService进行学习。
地址:http://www.webxml.com.cn/zh_cn/index.aspx
下面演示的就是如何通过该网站提供的手机号码归属地查询WebService服务查询号码归属地
调用地址http://webservice.webxml.com.cn/WebServices/MobileCodeWS.asmx?op=getMobileCodeInfo。
首先,将请求消息保存在XML文件中,然后使用$替换请求参数,如下:
mobilesoap.xml

既然是调用WebService,我们首先的搭建WebService服务器。为了便于操作,我们就使用网上免费的WebService进行学习。
地址:http://www.webxml.com.cn/zh_cn/index.aspx
下面演示的就是如何通过该网站提供的手机号码归属地查询WebService服务查询号码归属地
调用地址http://webservice.webxml.com.cn/WebServices/MobileCodeWS.asmx?op=getMobileCodeInfo。
首先,将请求消息保存在XML文件中,然后使用$替换请求参数,如下:
mobilesoap.xml
[html] view plain copy
  1. <spanstyle="font-size:16px;"><?xmlversion="1.0"encoding="utf-8"?>
  2. <soap12:Envelopexmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns:xsd="http://www.w3.org/2001/XMLSchema"xmlns:soap12="http://www.w3.org/2003/05/soap-envelope">
  3. <soap12:Body>
  4. <getMobileCodeInfoxmlns="http://WebXml.com.cn/">
  5. <mobileCode>$mobile</mobileCode>
  6. <userID></userID>
  7. </getMobileCodeInfo>
  8. </soap12:Body>
  9. </soap12:Envelope></span>
其次,设计MainActivity布局文件,
main.xml
[html] view plain copy
  1. <spanstyle="font-size:16px;"><?xmlversion="1.0"encoding="utf-8"?>
  2. <LinearLayout
  3. xmlns:android="http://schemas.android.com/apk/res/android"
  4. android:orientation="vertical"
  5. android:layout_width="fill_parent"
  6. android:layout_height="fill_parent">
  7. <TextView
  8. android:layout_width="fill_parent"
  9. android:layout_height="wrap_content"
  10. android:text="手机号码"/>
  11. <EditText
  12. android:id="@+id/mobileNum"
  13. android:layout_width="fill_parent"
  14. android:layout_height="wrap_content"
  15. android:text=""
  16. />
  17. <Button
  18. android:id="@+id/btnSearch"
  19. android:layout_width="wrap_content"
  20. android:layout_height="wrap_content"
  21. android:text="查询"
  22. />
  23. <TextView
  24. android:id="@+id/mobileAddress"
  25. android:layout_width="fill_parent"
  26. android:layout_height="wrap_content"
  27. />
  28. </LinearLayout></span>
下面贴出MainActivity,
在Android中调用WebService还是比较简单的:请求webservice,获取服务响应的数据,解析后并显示。
[java] view plain copy
  1. <spanstyle="font-size:16px;">packagecom.szy.webservice;
  2. importjava.io.ByteArrayOutputStream;
  3. importjava.io.InputStream;
  4. importjava.io.OutputStream;
  5. importjava.net.HttpURLConnection;
  6. importjava.net.URL;
  7. importjava.util.HashMap;
  8. importjava.util.Map;
  9. importjava.util.regex.Matcher;
  10. importjava.util.regex.Pattern;
  11. importorg.xmlpull.v1.XmlPullParser;
  12. importandroid.app.Activity;
  13. importandroid.os.Bundle;
  14. importandroid.util.Log;
  15. importandroid.util.Xml;
  16. importandroid.view.View;
  17. importandroid.widget.Button;
  18. importandroid.widget.EditText;
  19. importandroid.widget.TextView;
  20. importandroid.widget.Toast;
  21. /**
  22. *@authorcoolszy
  23. *@date2012-3-8
  24. *@bloghttp://blog.92coding.com
  25. */
  26. publicclassMainActivityextendsActivity
  27. {
  28. privateEditTextmobileNum;
  29. privateTextViewmobileAddress;
  30. privatestaticfinalStringTAG="MainActivity";
  31. @Override
  32. publicvoidonCreate(BundlesavedInstanceState)
  33. {
  34. super.onCreate(savedInstanceState);
  35. setContentView(R.layout.main);
  36. mobileNum=(EditText)this.findViewById(R.id.mobileNum);
  37. mobileAddress=(TextView)this.findViewById(R.id.mobileAddress);
  38. ButtonbtnSearch=(Button)this.findViewById(R.id.btnSearch);
  39. btnSearch.setOnClickListener(newView.OnClickListener()
  40. {
  41. @Override
  42. publicvoidonClick(Viewv)
  43. {
  44. //获取电话号码
  45. Stringmobile=mobileNum.getText().toString();
  46. //读取xml文件
  47. InputStreaminStream=this.getClass().getClassLoader().getResourceAsStream("mobilesoap.xml");
  48. try
  49. {
  50. //显示电话号码地理位置,该段代码不合理,仅供参考
  51. mobileAddress.setText(getMobileAddress(inStream,mobile));
  52. }catch(Exceptione)
  53. {
  54. Log.e(TAG,e.toString());
  55. Toast.makeText(MainActivity.this,"查询失败",1).show();
  56. }
  57. }
  58. });
  59. }
  60. /**
  61. *获取电话号码地理位置
  62. *
  63. *@paraminStream
  64. *@parammobile
  65. *@return
  66. *@throwsException
  67. */
  68. privateStringgetMobileAddress(InputStreaminStream,Stringmobile)throwsException
  69. {
  70. //替换xml文件中的电话号码
  71. Stringsoap=readSoapFile(inStream,mobile);
  72. byte[]data=soap.getBytes();
  73. //提交Post请求
  74. URLurl=newURL("http://webservice.webxml.com.cn/WebServices/MobileCodeWS.asmx");
  75. HttpURLConnectionconn=(HttpURLConnection)url.openConnection();
  76. conn.setRequestMethod("POST");
  77. conn.setConnectTimeout(5*1000);
  78. conn.setDoOutput(true);
  79. conn.setRequestProperty("Content-Type","application/soap+xml;charset=utf-8");
  80. conn.setRequestProperty("Content-Length",String.valueOf(data.length));
  81. OutputStreamoutStream=conn.getOutputStream();
  82. outStream.write(data);
  83. outStream.flush();
  84. outStream.close();
  85. if(conn.getResponseCode()==200)
  86. {
  87. //解析返回信息
  88. returnparseResponseXML(conn.getInputStream());
  89. }
  90. return"Error";
  91. }
  92. privateStringreadSoapFile(InputStreaminStream,Stringmobile)throwsException
  93. {
  94. //从流中获取文件信息
  95. byte[]data=readInputStream(inStream);
  96. Stringsoapxml=newString(data);
  97. //占位符参数
  98. Map<String,String>params=newHashMap<String,String>();
  99. params.put("mobile",mobile);
  100. //替换文件中占位符
  101. returnreplace(soapxml,params);
  102. }
  103. /**
  104. *读取流信息
  105. *
  106. *@paraminputStream
  107. *@return
  108. *@throwsException
  109. */
  110. privatebyte[]readInputStream(InputStreaminputStream)throwsException
  111. {
  112. byte[]buffer=newbyte[1024];
  113. intlen=-1;
  114. ByteArrayOutputStreamoutSteam=newByteArrayOutputStream();
  115. while((len=inputStream.read(buffer))!=-1)
  116. {
  117. outSteam.write(buffer,0,len);
  118. }
  119. outSteam.close();
  120. inputStream.close();
  121. returnoutSteam.toByteArray();
  122. }
  123. /**
  124. *替换文件中占位符
  125. *
  126. *@paramxml
  127. *@paramparams
  128. *@return
  129. *@throwsException
  130. */
  131. privateStringreplace(Stringxml,Map<String,String>params)throwsException
  132. {
  133. Stringresult=xml;
  134. if(params!=null&&!params.isEmpty())
  135. {
  136. for(Map.Entry<String,String>entry:params.entrySet())
  137. {
  138. Stringname="\\$"+entry.getKey();
  139. Patternpattern=Pattern.compile(name);
  140. Matchermatcher=pattern.matcher(result);
  141. if(matcher.find())
  142. {
  143. result=matcher.replaceAll(entry.getValue());
  144. }
  145. }
  146. }
  147. returnresult;
  148. }
  149. /**
  150. *解析XML文件
  151. *@paraminStream
  152. *@return
  153. *@throwsException
  154. */
  155. privatestaticStringparseResponseXML(InputStreaminStream)throwsException
  156. {
  157. XmlPullParserparser=Xml.newPullParser();
  158. parser.setInput(inStream,"UTF-8");
  159. inteventType=parser.getEventType();//产生第一个事件
  160. while(eventType!=XmlPullParser.END_DOCUMENT)
  161. {
  162. //只要不是文档结束事件
  163. switch(eventType)
  164. {
  165. caseXmlPullParser.START_TAG:
  166. Stringname=parser.getName();//获取解析器当前指向的元素的名称
  167. if("getMobileCodeInfoResult".equals(name))
  168. {
  169. returnparser.nextText();
  170. }
  171. break;
  172. }
  173. eventType=parser.next();
  174. }
  175. returnnull;
  176. }
  177. }</span>
最后注意,由于需要访问网络,需要加上权限
[html] view plain copy
  1. <spanstyle="font-size:16px;"><uses-permissionandroid:name="android.permission.INTERNET"/></span>

通过上面简单的例子,相信大家已经学习了如何在Android中调用WebService,最后运行效果:



更多相关文章

  1. 一款常用的 Squid 日志分析工具
  2. GitHub 标星 8K+!一款开源替代 ls 的工具你值得拥有!
  3. “罗永浩抖音首秀”销售数据的可视化大屏是怎么做出来的呢?
  4. Nginx系列教程(三)| 一文带你读懂Nginx的负载均衡
  5. RHEL 6 下 DHCP+TFTP+FTP+PXE+Kickstart 实现无人值守安装
  6. Linux 环境下实战 Rsync 备份工具及配置 rsync+inotify 实时同步
  7. 不吹不黑!GitHub 上帮助人们学习编码的 12 个资源,错过血亏...
  8. Android(安卓)open failed: EBUSY (Device or resource busy)
  9. Android(安卓)NDK开发“Hello World NDK”

随机推荐

  1. Android 访问权限许可大全
  2. Android UI开发第二十六篇——Fragment间
  3. Android 源码阅读之SMS
  4. Android积木之LayoutParams使用
  5. Android打开WIFI或者移动网络的代码实现
  6. Android 中文字符转UTF-8编码
  7. Android InputMethodManager 导致的内存
  8. android 读取网络 xml 数据
  9. android - mvp实现商品详情页面【仿】京
  10. Android 的常用控件(下拉,日期,时间,单项,多项