1.写作背景:

  笔者想实现android调用webservice,可是网上全是不管对与错乱转载的文章,结果不但不能解决问题,只会让人心烦,所以笔者决定将自己整理好的能用的android调用webservice的实现分享给大家,供以后遇到相同需求的人能少走弯路。

  源码使用android studio编写,可以在github上面下载观看:https://github.com/jhscpang/TestWebSwervice。

2.具体实现:

  本文的重点是android怎么调用webservice而不是用哪个webservice,所以这里就用网上传的比较多的计算来电归属地的webservice进行测试。这个webservice地址为:http://webservice.webxml.com.cn/WebServices/MobileCodeWS.asmx?wsdl。

用浏览器访问这个网址可以看到如下界面:

图中被圈起来的部分1说明soap版本为12, 被圈起来的部分2说明了namespace地址,这两个值稍后在代码中能用到。

图中被圈起来的部分说明了调用的方法的名字,里面的说明文档告诉了输入参数和返回值等信息,这些信息稍后代码中也会用到。

  下面写请求webservice的方法,代码如下, 具体每句的解释有备注:

  1. /**
  2. * 手机号段归属地查询
  3. *
  4. * @param phoneSec 手机号段
  5. */
  6. public String getRemoteInfo(String phoneSec) throws Exception{
  7. String WSDL_URI = "http://webservice.webxml.com.cn/WebServices/MobileCodeWS.asmx?WSDL";//wsdl 的uri
  8. String namespace = "http://WebXml.com.cn/";//namespace
  9. String methodName = "getMobileCodeInfo";//要调用的方法名称
  10.  
  11. SoapObject request = new SoapObject(namespace, methodName);
  12. // 设置需调用WebService接口需要传入的两个参数mobileCode、userId
  13. request.addProperty("mobileCode", phoneSec);
  14. request.addProperty("userId", "");
  15.  
  16. //创建SoapSerializationEnvelope 对象,同时指定soap版本号(之前在wsdl中看到的)
  17. SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapSerializationEnvelope.VER12);
  18. envelope.bodyOut = request;//由于是发送请求,所以是设置bodyOut
  19. envelope.dotNet = true;//由于是.net开发的webservice,所以这里要设置为true
  20.  
  21. HttpTransportSE httpTransportSE = new HttpTransportSE(WSDL_URI);
  22. httpTransportSE.call(null, envelope);//调用
  23.  
  24. // 获取返回的数据
  25. SoapObject object = (SoapObject) envelope.bodyIn;
  26. // 获取返回的结果
  27. result = object.getProperty(0).toString();
  28. Log.d("debug",result);
  29. return result;
  30.  
  31. }

  因为调用webservice属于联网操作,因此不能再UI线程中执行访问webservice,为了便于将结果反馈给UI线程,采用AsyncTask线程,代码如下:

  1. class QueryAddressTask extends AsyncTask<String, Integer, String> {
  2. @Override
  3. protected String doInBackground(String... params) {
  4. // 查询手机号码(段)信息*/
  5. try {
  6. result = getRemoteInfo(params[0]);
  7.  
  8. } catch (Exception e) {
  9. e.printStackTrace();
  10. }
  11. //将结果返回给onPostExecute方法
  12. return result;
  13. }
  14.  
  15. @Override
  16. //此方法可以在主线程改变UI
  17. protected void onPostExecute(String result) {
  18. // 将WebService返回的结果显示在TextView中
  19. resultView.setText(result);
  20. }
  21. }

  然后在主线程中给用户设置使用该功能的方法,代码如下:

  1. private EditText phoneSecEditText;
  2. private TextView resultView;
  3. private Button queryButton;
  4. private String result;
  5.  
  6. @Override
  7. protected void onCreate(Bundle savedInstanceState) {
  8. super.onCreate(savedInstanceState);
  9. setContentView(R.layout.activity_main);
  10.  
  11. phoneSecEditText = (EditText) findViewById(R.id.phone_sec);
  12. resultView = (TextView) findViewById(R.id.result_text);
  13. queryButton = (Button) findViewById(R.id.query_btn);
  14.  
  15. queryButton.setOnClickListener(new OnClickListener() {
  16. @Override
  17. public void onClick(View v) {
  18. // 手机号码(段)
  19. String phoneSec = phoneSecEditText.getText().toString().trim();
  20. // 简单判断用户输入的手机号码(段)是否合法
  21. if ("".equals(phoneSec) || phoneSec.length() < 7) {
  22. // 给出错误提示
  23. phoneSecEditText.setError("您输入的手机号码(段)有误!");
  24. phoneSecEditText.requestFocus();
  25. // 将显示查询结果的TextView清空
  26. resultView.setText("");
  27. return;
  28. }
  29.  
  30. //启动后台异步线程进行连接webService操作,并且根据返回结果在主线程中改变UI
  31. QueryAddressTask queryAddressTask = new QueryAddressTask();
  32. //启动后台任务
  33. queryAddressTask.execute(phoneSec);
  34.  
  35. }
  36. });
  37. }

  布局文件如下:

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  3. android:orientation="vertical"
  4. android:layout_width="fill_parent"
  5. android:layout_height="fill_parent"
  6. android:paddingTop="5dip"
  7. android:paddingLeft="5dip"
  8. android:paddingRight="5dip"
  9. >
  10. <TextView
  11. android:layout_width="fill_parent"
  12. android:layout_height="wrap_content"
  13. android:text="手机号码(段):"
  14. />
  15. <EditText android:id="@+id/phone_sec"
  16. android:layout_width="fill_parent"
  17. android:layout_height="wrap_content"
  18. android:inputType="textPhonetic"
  19. android:singleLine="true"
  20. android:hint="例如:1398547"
  21. />
  22. <Button android:id="@+id/query_btn"
  23. android:layout_width="wrap_content"
  24. android:layout_height="wrap_content"
  25. android:layout_gravity="right"
  26. android:text="查询"
  27. />
  28. <TextView android:id="@+id/result_text"
  29. android:layout_width="wrap_content"
  30. android:layout_height="wrap_content"
  31. android:layout_gravity="center_horizontal|center_vertical"
  32. />
  33. </LinearLayout>

  AndroidManifest文件如下:

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <manifest xmlns:android="http://schemas.android.com/apk/res/android"
  3. package="com.jhsc.testwebservice" >
  4.  
  5. <uses-permission android:name="android.permission.INTERNET" />
  6.  
  7. <application
  8. android:allowBackup="true"
  9. android:icon="@mipmap/ic_launcher"
  10. android:label="@string/app_name"
  11. android:supportsRtl="true"
  12. android:theme="@style/AppTheme" >
  13. <activity android:name=".MainActivity" >
  14. <intent-filter>
  15. <action android:name="android.intent.action.MAIN" />
  16.  
  17. <category android:name="android.intent.category.LAUNCHER" />
  18. </intent-filter>
  19. </activity>
  20. </application>
  21.  
  22. </manifest>

  运行效果如下图:

纠正网上乱传的android调用Webservice方法。的更多相关文章

  1. Android调用WebService

    这两天给老师做地铁app的demo,与后台的交互要用WebService,还挺麻烦的.所以想写点,希望有用. Web Services(Web服务)是一个用于支持网络间不同机器互操作的软件系统,它是一 ...

  2. 网摘Android调用WebService

    这边特别注意调用的.net WCF 接口的绑定方式.以前一直用的wxHttpbinding,一直连不上.改成BasicHTTPbinding就能连上了 上篇文章已经对Web Service及其相关知识 ...

  3. 第十五章:Android 调用WebService(.net平台)

    什么是webservice? Web service是一个平台独立的,低耦合的,自包含的.基于可编程的web的应用程序,可使用开放的XML(标准通用标记语言下的一个子集)标准来描述.发布.发现.协调和 ...

  4. Android调用WebService(转)

    Android调用WebService WebService是一种基于SOAP协议的远程调用标准,通过 webservice可以将不同操作系统平台.不同语言.不同技术整合到一块.在Android SD ...

  5. Android 调用webService(.net平台)

    什么是webservice? Web service是一个平台独立的,低耦合的,自包含的.基于可编程的web的应用程序,可使用开放的XML(标准通用标记语言下的一个子集)标准来描述.发布.发现.协调和 ...

  6. Java调用WebService方法总结(8)--soap.jar调用WebService

    Apache的soap.jar是一种历史很久远的WebService技术,大概是2001年左右的技术,所需soap.jar可以在http://archive.apache.org/dist/ws/so ...

  7. Java调用WebService方法总结(6)--XFire调用WebService

    XFire是codeHaus组织提供的一个WebService开源框架,目前已被Apache的CXF所取代,已很少有人用了,这里简单记录下其调用WebService使用方法.官网现已不提供下载,可以到 ...

  8. winform客户端程序第一次调用webservice方法很慢的解决方法

    .net2.0的winform客户端最常用的与服务端通信方式是通过webservice,最近在用dottrace对客户端做性能测试的时候发现,客户端程序启动以后,第一次调用某一个webservice的 ...

  9. Java调用WebService方法总结(9,end)--Http方式调用WebService

    Http方式调用WebService,直接发送soap消息到服务端,然后自己解析服务端返回的结果,这种方式比较简单粗暴,也很好用:soap消息可以通过SoapUI来生成,也很方便.文中所使用到的软件版 ...

随机推荐

  1. Altium Designer 快捷键使用整理

    Altium Designer 快捷键 一.原理图部分 1.原理图元件自动编号 原理图中快捷键 T+A 2.原理图与PCB交互设计查找 原理图中选中一个元件跳转到PCB中相应的位置T+S 3.原理图中 ...

  2. hdu1251统计难题(trie)

    统计难题 Time Limit: 4000/2000 MS (Java/Others)    Memory Limit: 131070/65535 K (Java/Others)Total Submi ...

  3. compileReleaseJavaWithJavac

    如果你打release 包的时候,出现这个问题,那么请你先跑一下程序,肯定是有什么方法名,或者什么东西没找到. release 的时候不会报错,只有你跑的时候才会报错.

  4. linux centos7--linux和window共享文件(samba)

    这里以VMWARE与主控真机来做实现实现 由于SMB在centos中自带,所以,无需像网上说的样子,要这删除,那卸载,直接搜索是否存在SAMBA的安装文件 一 查询包是否存在 [root@localh ...

  5. 分别用反射、编程接口的方式创建DataFrame

    1.通过反射的方式 使用反射来推断包含特定数据类型的RDD,这种方式代码比较少,简洁,只要你会知道元数据信息时什么样,就可以使用了 代码如下: import org.apache.spark.sql. ...

  6. VSX-3 VSCT文件

    关于VSPackage中的VSCT,算是VSX开发中比较重要的一个成员. 我这里给出LearnVSXNow!系列文章关于VSCT的链接,除了#14有译文. #14 #18 #25 看完上面几篇文章,也 ...

  7. MySQL 5.7.18 压缩包版配置记录

    1.解压到一个目录(建议根目录),比如:D:\mysql2.在系统Path中添加 D:\mysql\bin3.这个版本不带my-default.ini,需要自己写,放在D:\mysql\my.ini, ...

  8. 《Cracking the Coding Interview》——第7章:数学和概率论——题目5

    2014-03-20 02:20 题目:给定二维平面上两个正方形,用一条直线将俩方块划分成面积相等的两部分. 解法:穿过对称中心的线会将面积等分,所以连接两个中心即可.如果两个中心恰好重合,那么任意穿 ...

  9. B树、B-树、B+树、B*树 红黑树

    转载自:http://blog.csdn.net/quitepig/article/details/8041308 B树 即二叉搜索树: 1.所有非叶子结点至多拥有两个儿子(Left和Right): ...

  10. shell之echo and printf

    #!/bin/sh _________echo___________#read name #echo "$name It is a test" #read命令从标准的输入中读取一行 ...