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的方法,代码如下, 具体每句的解释有备注:

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

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

 class QueryAddressTask extends AsyncTask<String, Integer, String> {
@Override
protected String doInBackground(String... params) {
// 查询手机号码(段)信息*/
try {
result = getRemoteInfo(params[0]); } catch (Exception e) {
e.printStackTrace();
}
//将结果返回给onPostExecute方法
return result;
} @Override
//此方法可以在主线程改变UI
protected void onPostExecute(String result) {
// 将WebService返回的结果显示在TextView中
resultView.setText(result);
}
}

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

private EditText phoneSecEditText;
private TextView resultView;
private Button queryButton;
private String result; @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main); phoneSecEditText = (EditText) findViewById(R.id.phone_sec);
resultView = (TextView) findViewById(R.id.result_text);
queryButton = (Button) findViewById(R.id.query_btn); queryButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// 手机号码(段)
String phoneSec = phoneSecEditText.getText().toString().trim();
// 简单判断用户输入的手机号码(段)是否合法
if ("".equals(phoneSec) || phoneSec.length() < 7) {
// 给出错误提示
phoneSecEditText.setError("您输入的手机号码(段)有误!");
phoneSecEditText.requestFocus();
// 将显示查询结果的TextView清空
resultView.setText("");
return;
} //启动后台异步线程进行连接webService操作,并且根据返回结果在主线程中改变UI
QueryAddressTask queryAddressTask = new QueryAddressTask();
//启动后台任务
queryAddressTask.execute(phoneSec); }
});
}

  布局文件如下:

<?xml version="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"
android:paddingTop="5dip"
android:paddingLeft="5dip"
android:paddingRight="5dip"
>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="手机号码(段):"
/>
<EditText android:id="@+id/phone_sec"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:inputType="textPhonetic"
android:singleLine="true"
android:hint="例如:1398547"
/>
<Button android:id="@+id/query_btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:text="查询"
/>
<TextView android:id="@+id/result_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal|center_vertical"
/>
</LinearLayout>

  AndroidManifest文件如下:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.jhsc.testwebservice" > <uses-permission android:name="android.permission.INTERNET" /> <application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme" >
<activity android:name=".MainActivity" >
<intent-filter>
<action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application> </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. 自己定义的TryParse()

    out 参数的练习,自己定义的TryParse()... 一开始写错了,错在:判断str[i] >= '0'&& str[i]<='9'时,把str[i]当数字去判断了.. ...

  2. 使用Subversion进行源代码管理(二):创建和发布版本库[转]

    原文出处: http://www.blogjava.net/youxia/archive/2007/10/23/155372.html 我的上一篇随笔讲了怎么使用Subversion客户端去连接服务器 ...

  3. 解决 ld: library not found for -lPods的问题

    现在打开有pods建好的workspace文件,尝试编译,会报ld: library not found for -lPods错误,原因就是工程里面的设置项覆盖了pods中xcconfig中的设置.解 ...

  4. flask-ssti,xss的防止

    源码 import uuid from flask import Flask, request, make_response, session,render_template, url_for, re ...

  5. python - web自动化测试 - 元素操作 - 窗口切换

    # -*- coding:utf-8 -*- ''' @project: web学习 @author: Jimmy @file: 元素操作-切换.py @ide: PyCharm Community ...

  6. CentOS 6.3下安装Vsftp,虚拟用户

    CentOS 6.3下安装Vsftp,虚拟用户一.安装:1.安装Vsftpd服务相关部件:[root@linuxidc.com ~]# yum install vsftpd*Dependencies ...

  7. HDU 4655 Cut Pieces 找规律+简单计数

    解法参考:http://blog.csdn.net/a601025382s/article/details/9840125 #include <cstdio> #include <c ...

  8. 史林枫:sqlserver数据库中数据日志的压缩及sqlserver占用内存管理设置

    使用sqlserver和IIS开发.net B/S程序时,数据量逐渐增多,用户也逐渐增多,那么服务器的稳定性就需要维护了.数据库如何占用更小内存,无用的日志如何瞬间清空? 今天在给一个客户维护网站的时 ...

  9. 【bzoj1511】[POI2006]OKR-Periods of Words KMP-next数组

    原文地址:http://www.cnblogs.com/GXZlegend/p/6827027.html 题目描述 一个串是有限个小写字符的序列,特别的,一个空序列也可以是一个串. 一个串P是串A的前 ...

  10. GCC 中 -L、-rpath和-rpath-link的区别

    GCC 中 -L.-rpath和-rpath-link的区别 来源 http://blog.csdn.net/q1302182594/article/details/42102961 关于这3个参数的 ...