纠正网上乱传的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>
运行效果如下图:
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步