纠正网上乱传的android调用Webservice方法。

 

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>

  运行效果如下图:

soap协议jar包下载
2.54版本:ksoap2-android 2.54.jar
http://www.runoob.com/try/download/ksoap2-android-assembly-2.5.4-jar-with-dependencies.jar
3.30版本:ksoap2-android 3.30.jar
http://www.runoob.com/try/download/ksoap2-android-assembly-3.3.0-jar-with-dependencies.jar

自:https://www.cnblogs.com/superpang/p/4911422.html

(转)Android访问webservice的更多相关文章

  1. 如何解析android访问webservice返回的SoapObject数据(可用)

    怎么解析android访问webservice返回的SoapObject数据 本帖最后由 kkDragon123 于 2013-03-26 15:50:07 编辑 我的数据如下:mingdanResp ...

  2. Android访问WebService的两种方法

    首先解释一下WebService:WebService是一种基于SOAP协议的远程调用标准.通过WebService可以将不同操作系统平台,不同语言.不同技术整合到一起.详细见:http://baik ...

  3. android访问webservice

    // nameSpace 命名空间,methodName:方法名字:maps:参数集合:webserviceUrl:访问的webservice的网址:比如:http://17.18.199.100:8 ...

  4. Mono for android 访问Webservice和WebApi以及获取和解析JSON

    先看效果,注意:(1)这里由于我的模拟器不支持中文输入,所以,对于这张效果图,我是直接在代码中写死了我的查询城市,在下面的代码中我是没有把要查询的城市写死的. (2)读者要想成功使用本示例的所有代码的 ...

  5. Android实现KSOAP2访问WebService

    Android实现KSOAP2访问WebService 开发工具:Andorid Studio 1.3 运行环境:Android 4.4 KitKat 代码实现 写一个工具类来给主界面使用,作用是使用 ...

  6. Android局域网访问webservice以及其中的一些问题

    应老师的要求,要做个安卓app,实现备份app上的数据到服务器上的mongodb上,网上搜了下相关的实现方式.利用webservice技术,具体来说就是客户端直接调用服务器端的接口.之前从来没接触这玩 ...

  7. WebService---Android中访问WebService接口的方法

     最近公司有个项目需要从Android平台访问WebService接口,实现向发布的函数传递对象.在网上找了一些资料,发现使用ksoap2可以调用WebService传递对象.   需要引入ksoap ...

  8. Android平台调用WebService详解

    上篇文章已经对Web Service及其相关知识进行了介绍(Android开发之WebService介绍 ),相信有的朋友已经忍耐不住想试试在Android应用中调用Web Service.本文将通过 ...

  9. 解决android开发webservice的发布与数据库连接的问题

    由于app后续开发的需要,移植了两次webservice和数据库,遇到了不少问题,也花费了很多时间,实践告诉我要学会寻找问题的根源,这样才能在开发中节省时间,尽快解决问题!好,废话不多说,转入正题…… ...

随机推荐

  1. 【转载】Java的Vector,ArrayList,LinkedList

    首先看这两类都实现List接口,而List接口一共有三个实现类,分别是ArrayList.Vector和LinkedList.List用于存放多个元素,能够维护元素的次序,并且允许元素的重复.3个具体 ...

  2. css position absolute相对于父元素的设置方式

    手机赚钱怎么赚,给大家推荐一个手机赚钱APP汇总平台:手指乐(http://www.szhile.com/),辛苦搬砖之余用闲余时间动动手指,就可以日赚数百元 大家知道css的position abs ...

  3. 手动使用I2C协议写入24C02C

    刚尝试用AT89C52单片机使用IIC总线协议读写AT24C02C,我忽然想能否用手动调整开关的方式写入AT24C02C?于是,便尝试了一下,结果果然成功了. 关于IIC总线,这篇文章写的很详细:ht ...

  4. python函数定义中引用外部变量的一个问题

    如果在函数定义的默认值中引用了一个外部变量,如下所示 x = 3 def func(a = x): print(a, x) 那么a的默认值就会是3, 但是print语句中的x会是调用时的x值 lamb ...

  5. asp.net core 3.1 入口:Program.cs中的Main函数

    本文分析Program.cs 中Main()函数中代码的运行顺序分析asp.net core程序的启动,重点不是剖析源码,而是理清程序开始时执行的顺序.到底用了哪些实例,哪些法方. asp.net c ...

  6. StarUML之八、StarUML的Entity-Relationship Diagram(实体关系图)示例

    数据库表关系设计也是常有场景,本章介绍如何设计一个实体关系图 1:新建项目,在Model Explore中Add Diagram | ER Diagram到指定的元素中: 2:从Toolbox中创建E ...

  7. HA: Dhanush Vulnhub Walkthrough

    靶机下载链接: https://www.vulnhub.com/entry/ha-dhanush,396/ 主机扫描: 主机端口扫描: HTTP目录爬取 使用dirb dirsearch 爬取均未发现 ...

  8. Android中自定义xml文件给Spinner下拉框赋值并获取下拉选中的值

    场景 实现效果如下 注: 博客: https://blog.csdn.net/badao_liumang_qizhi 关注公众号 霸道的程序猿 获取编程相关电子书.教程推送与免费下载. 实现 将布局改 ...

  9. PG数据库常用操作

    全量迁移 备份数据 $ pg_dump -h 172.19.235.145 -U <username> -d <database> > 20180704_dbpe.sql ...

  10. 「Flink」Flink中的时间类型

    Flink中的时间类型和窗口是非常重要概念,是学习Flink必须要掌握的两个知识点. Flink中的时间类型 时间类型介绍 Flink流式处理中支持不同类型的时间.分为以下几种: 处理时间 Flink ...