纠正网上乱传的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. codewars--js--Simple string expansion+ repeat(),includes()方法

    问题描述: Consider the following expansion: solve("3(ab)") = "ababab" -- "ab&qu ...

  2. 图解Java设计模式之设计模式面试题

    图解Java设计模式之设计模式面试题 1.1 Java设计模式内容介绍 1.1.1 先看几个经典的面试题 1.1.2 设计模式的重要性 1.1 Java设计模式内容介绍 1.1.1 先看几个经典的面试 ...

  3. Http API触发小程序云函数案例

    1.创建云函数 在云开发中创建云函数(sum,调用需要两个参数:a.b): 2.invokeCloudFunction触发云函数 const request = require('request'); ...

  4. 常见Linux命令学习

    Linux命令学习 命令分类: 文件处理命令 权限管理命令 文件搜索命令 帮助命令 用户管理命令 压缩解压命令 网络命令 关机重启命令 1.文件处理命令 命令格式:命令 [-选项] [参数] 例:ls ...

  5. MFC/QT 学习笔记(四)——MFC基于对话框学习控件(上)

    新建项目->MFC模板->MFC应用程序->应用程序类型:基于对话框->...OK 解决方案资源管理器->资源文件->xxx.rc->进入:资源视图-> ...

  6. PMP--2. 项目启动前准备工作

    ####################################################### 概述:在第一章节的1.1-1.7中基本都是介绍的<PMBOK>的理论概念以及 ...

  7. 阿里云服务器Web Deploy配置和使用Visual Studio进行Web项目发布部署遇到的坑

    阿里云的服务器一直闲着,烧着银子,当初花几千大洋开通,本想弄信息化的项目为所帮扶的贫困户脱贫助手,不想势单力薄,一直没有找到好的项目.最近大家都在众志成城抗击新肺疫情,于是又想能不能尽点自己的力量,于 ...

  8. es6异步解决方案

    最初使用回调函数 ​ 由于最初j s官方没有明确的规范,各种第三方库中封装的异步函数中传的回调函数中的参数没有明确的规范, 没有明确各个参数的意义, 不便于使用. ​ 但是node中有明确的规范 ​ ...

  9. 特殊符号unicode编码

    包括箭头类.基本形状类.货币类.数学类.音乐符号类.对错类.星星类.星座类.国际象棋类.扑克牌类.希腊字母.十字类.法律符号.标点符号,详情见以下网址:http://caibaojian.com/un ...

  10. Python之基础、细节

    引号的用法 单引号对 ' ' :表示字符串,可以换行 双引号对 " " :表示字符串 三引号对 ''' ''' 和 """ ""& ...