Android通信方式(三)------WebService补充
16lz
2021-01-25
某些情况下我们可能需要与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
地址: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
- <spanstyle="font-size:16px;"><?xmlversion="1.0"encoding="utf-8"?>
- <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">
- <soap12:Body>
- <getMobileCodeInfoxmlns="http://WebXml.com.cn/">
- <mobileCode>$mobile</mobileCode>
- <userID></userID>
- </getMobileCodeInfo>
- </soap12:Body>
- </soap12:Envelope></span>
main.xml
[html] view plain copy
- <spanstyle="font-size:16px;"><?xmlversion="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">
- <TextView
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- android:text="手机号码"/>
- <EditText
- android:id="@+id/mobileNum"
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- android:text=""
- />
- <Button
- android:id="@+id/btnSearch"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:text="查询"
- />
- <TextView
- android:id="@+id/mobileAddress"
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- />
- </LinearLayout></span>
在Android中调用WebService还是比较简单的:请求webservice,获取服务响应的数据,解析后并显示。
[java] view plain copy
- <spanstyle="font-size:16px;">packagecom.szy.webservice;
- importjava.io.ByteArrayOutputStream;
- importjava.io.InputStream;
- importjava.io.OutputStream;
- importjava.net.HttpURLConnection;
- importjava.net.URL;
- importjava.util.HashMap;
- importjava.util.Map;
- importjava.util.regex.Matcher;
- importjava.util.regex.Pattern;
- importorg.xmlpull.v1.XmlPullParser;
- importandroid.app.Activity;
- importandroid.os.Bundle;
- importandroid.util.Log;
- importandroid.util.Xml;
- importandroid.view.View;
- importandroid.widget.Button;
- importandroid.widget.EditText;
- importandroid.widget.TextView;
- importandroid.widget.Toast;
- /**
- *@authorcoolszy
- *@date2012-3-8
- *@bloghttp://blog.92coding.com
- */
- publicclassMainActivityextendsActivity
- {
- privateEditTextmobileNum;
- privateTextViewmobileAddress;
- privatestaticfinalStringTAG="MainActivity";
- @Override
- publicvoidonCreate(BundlesavedInstanceState)
- {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.main);
- mobileNum=(EditText)this.findViewById(R.id.mobileNum);
- mobileAddress=(TextView)this.findViewById(R.id.mobileAddress);
- ButtonbtnSearch=(Button)this.findViewById(R.id.btnSearch);
- btnSearch.setOnClickListener(newView.OnClickListener()
- {
- @Override
- publicvoidonClick(Viewv)
- {
- //获取电话号码
- Stringmobile=mobileNum.getText().toString();
- //读取xml文件
- InputStreaminStream=this.getClass().getClassLoader().getResourceAsStream("mobilesoap.xml");
- try
- {
- //显示电话号码地理位置,该段代码不合理,仅供参考
- mobileAddress.setText(getMobileAddress(inStream,mobile));
- }catch(Exceptione)
- {
- Log.e(TAG,e.toString());
- Toast.makeText(MainActivity.this,"查询失败",1).show();
- }
- }
- });
- }
- /**
- *获取电话号码地理位置
- *
- *@paraminStream
- *@parammobile
- *@return
- *@throwsException
- */
- privateStringgetMobileAddress(InputStreaminStream,Stringmobile)throwsException
- {
- //替换xml文件中的电话号码
- Stringsoap=readSoapFile(inStream,mobile);
- byte[]data=soap.getBytes();
- //提交Post请求
- URLurl=newURL("http://webservice.webxml.com.cn/WebServices/MobileCodeWS.asmx");
- HttpURLConnectionconn=(HttpURLConnection)url.openConnection();
- conn.setRequestMethod("POST");
- conn.setConnectTimeout(5*1000);
- conn.setDoOutput(true);
- conn.setRequestProperty("Content-Type","application/soap+xml;charset=utf-8");
- conn.setRequestProperty("Content-Length",String.valueOf(data.length));
- OutputStreamoutStream=conn.getOutputStream();
- outStream.write(data);
- outStream.flush();
- outStream.close();
- if(conn.getResponseCode()==200)
- {
- //解析返回信息
- returnparseResponseXML(conn.getInputStream());
- }
- return"Error";
- }
- privateStringreadSoapFile(InputStreaminStream,Stringmobile)throwsException
- {
- //从流中获取文件信息
- byte[]data=readInputStream(inStream);
- Stringsoapxml=newString(data);
- //占位符参数
- Map<String,String>params=newHashMap<String,String>();
- params.put("mobile",mobile);
- //替换文件中占位符
- returnreplace(soapxml,params);
- }
- /**
- *读取流信息
- *
- *@paraminputStream
- *@return
- *@throwsException
- */
- privatebyte[]readInputStream(InputStreaminputStream)throwsException
- {
- byte[]buffer=newbyte[1024];
- intlen=-1;
- ByteArrayOutputStreamoutSteam=newByteArrayOutputStream();
- while((len=inputStream.read(buffer))!=-1)
- {
- outSteam.write(buffer,0,len);
- }
- outSteam.close();
- inputStream.close();
- returnoutSteam.toByteArray();
- }
- /**
- *替换文件中占位符
- *
- *@paramxml
- *@paramparams
- *@return
- *@throwsException
- */
- privateStringreplace(Stringxml,Map<String,String>params)throwsException
- {
- Stringresult=xml;
- if(params!=null&&!params.isEmpty())
- {
- for(Map.Entry<String,String>entry:params.entrySet())
- {
- Stringname="\\$"+entry.getKey();
- Patternpattern=Pattern.compile(name);
- Matchermatcher=pattern.matcher(result);
- if(matcher.find())
- {
- result=matcher.replaceAll(entry.getValue());
- }
- }
- }
- returnresult;
- }
- /**
- *解析XML文件
- *@paraminStream
- *@return
- *@throwsException
- */
- privatestaticStringparseResponseXML(InputStreaminStream)throwsException
- {
- XmlPullParserparser=Xml.newPullParser();
- parser.setInput(inStream,"UTF-8");
- inteventType=parser.getEventType();//产生第一个事件
- while(eventType!=XmlPullParser.END_DOCUMENT)
- {
- //只要不是文档结束事件
- switch(eventType)
- {
- caseXmlPullParser.START_TAG:
- Stringname=parser.getName();//获取解析器当前指向的元素的名称
- if("getMobileCodeInfoResult".equals(name))
- {
- returnparser.nextText();
- }
- break;
- }
- eventType=parser.next();
- }
- returnnull;
- }
- }</span>
[html] view plain copy
- <spanstyle="font-size:16px;"><uses-permissionandroid:name="android.permission.INTERNET"/></span>
通过上面简单的例子,相信大家已经学习了如何在Android中调用WebService,最后运行效果:
更多相关文章
- 一款常用的 Squid 日志分析工具
- GitHub 标星 8K+!一款开源替代 ls 的工具你值得拥有!
- “罗永浩抖音首秀”销售数据的可视化大屏是怎么做出来的呢?
- Nginx系列教程(三)| 一文带你读懂Nginx的负载均衡
- RHEL 6 下 DHCP+TFTP+FTP+PXE+Kickstart 实现无人值守安装
- Linux 环境下实战 Rsync 备份工具及配置 rsync+inotify 实时同步
- 不吹不黑!GitHub 上帮助人们学习编码的 12 个资源,错过血亏...
- Android(安卓)open failed: EBUSY (Device or resource busy)
- Android(安卓)NDK开发“Hello World NDK”