频道栏目
首页 > 资讯 > Android基础教程 > 正文

第104章、Android访问WebService(从零开始学Android)

16-02-02        来源:[db:作者]  
收藏   我要投稿
天气预报、手机归属地查询……,包括与SQL SERVER数据库远程交互都可以通过Web Service搞定。

准备工作:

(1)第一步,下载定位Android locSDK3.3。

(2)第二步,修改扩展名zip为jar

../201510/GridViewLiveTiles.html

请修改为:ksoap2-android-assembly-2.6.0-jar-with-dependencies.jar


准备工作至此已经结束。

 

一、工程配置

1、第一步,在工程里新建libs文件夹,将开发包里的ksoap2-android-assembly-2.6.0-jar-with-dependencies.jar拷贝到libs根目录下,拷贝完成后的工程目录如下图所示;

2、第二步:在工程属性->Java Build Path->Libraries中选择“Add External JARs”,选定ksoap2-android-assembly-2.6.0-jar-with-dependencies.jar,确定后返回。

通过以上两步操作后,您就可以正常使用Web Service的功能了。

二、设计界面

1、布局文件

打开res/layout/activity_main.xml文件。
输入以下代码:

[html] view plain copy
 
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     android:layout_width="fill_parent"  
  4.     android:layout_height="fill_parent"  
  5.     android:orientation="vertical" >  
  6.   
  7.     <EditText  
  8.         android:id="@+id/mobile"  
  9.         android:layout_width="match_parent"  
  10.         android:layout_height="wrap_content"  
  11.         android:inputType="phone" >  
  12.   
  13.         <requestFocus />  
  14.     </EditText>  
  15.   
  16.     <Button  
  17.         android:id="@+id/search"  
  18.         android:layout_width="wrap_content"  
  19.         android:layout_height="wrap_content"  
  20.         android:text="手机归属地查询" />  
  21.   
  22.     <TextView  
  23.         android:id="@+id/location"  
  24.         android:layout_width="wrap_content"  
  25.         android:layout_height="wrap_content"  
  26.         android:textSize="25sp" />  
  27.   
  28. </LinearLayout>  


三、程序文件

1、MainActivity.java
打开“src/com.genwoxue.baidulocation/MainActivity.java”文件。
然后输入以下代码:

[html] view plain copy
 
  1. package com.genwoxue.webservice;  
  2.   
  3.   
  4. import org.ksoap2.SoapEnvelope;  
  5. import org.ksoap2.serialization.SoapObject;  
  6. import org.ksoap2.serialization.SoapSerializationEnvelope;  
  7. import org.ksoap2.transport.HttpTransportSE;  
  8. import android.app.Activity;    
  9. import android.os.AsyncTask;  
  10. import android.os.Bundle;    
  11. import android.view.View;    
  12. import android.view.View.OnClickListener;  
  13. import android.widget.Button;  
  14. import android.widget.EditText;    
  15. import android.widget.TextView;    
  16.     
  17. public class MainActivity extends Activity {    
  18.     private EditText etMobile=null;    
  19.     private TextView tvLocation=null;   
  20.     private Button btnSearch=null;  
  21.       
  22.     public void onCreate(Bundle savedInstanceState) {    
  23.         super.onCreate(savedInstanceState);    
  24.         setContentView(R.layout.activity_main);    
  25.         etMobile = (EditText) findViewById(R.id.mobile);    
  26.         tvLocation = (TextView) findViewById(R.id.location);    
  27.         btnSearch=(Button)super.findViewById(R.id.search);  
  28.         btnSearch.setOnClickListener(new OnClickListener(){  
  29.             @Override  
  30.             public void onClick(View view){  
  31.                 String mobile = etMobile.getText().toString();    
  32.                 PageTask task = new PageTask();        
  33.                 task.execute(mobile);      
  34.            }  
  35.        });  
  36.     }    
  37.         
  38.         
  39.     /* 四个步骤:  
  40.      * (1)onPreExecute(),执行预处理,它运行于UI线程,  
  41.      * 可以为后台任务做一些准备工作,比如绘制一个进度条控件。  
  42.      * (2)doInBackground(Params...),后台进程执行的具体计算在这里实现,  
  43.      * doInBackground(Params...)是AsyncTask的关键,此方法必须重载。  
  44.      * 在这个方法内可以使用 publishProgress(Progress...)改变当前的进度值。  
  45.      * (3)onProgressUpdate(Progress...),运行于UI线程。如果  
  46.      * 在doInBackground(Params...) 中使用了publishProgress(Progress...),就会  
  47.      * 触发这个方法。在这里可以对进度条控件根据进度值做出具体的响应。  
  48.      * (4)onPostExecute(Result),运行于UI线程,可以对后台任务的结果做出处理,结果  
  49.      * 就是doInBackground(Params...)的返回值。此方法也要经常重载,如果Result为  
  50.      * null表明后台任务没有完成(被取消或者出现异常)。    *   
  51.      */  
  52.     class PageTask extends AsyncTask<String, Integer, String> {      
  53.         // (1)任务启动  
  54.         @Override          
  55.         protected void onPreExecute() {       
  56.             tvLocation.setText("task_started");          
  57.         }    
  58.           
  59.         //(2)后台执行:主要工作在这里实现(调用WebService就是在这里完成的)  
  60.         @Override            
  61.         protected String doInBackground(String... params) {     
  62.             String result = null;  
  63.             // 命名空间    
  64.             String nameSpace = "http://WebXml.com.cn/";    
  65.             // 调用的方法名称    
  66.             String methodName = "getMobileCodeInfo";    
  67.             // EndPoint    
  68.             String endPoint = "http://webservice.webxml.com.cn/WebServices/MobileCodeWS.asmx";    
  69.             // SOAP Action    
  70.             String soapAction = "http://WebXml.com.cn/getMobileCodeInfo";    
  71.         
  72.             // 指定WebService的命名空间和调用的方法名    
  73.             SoapObject rpc = new SoapObject(nameSpace, methodName);    
  74.         
  75.             // 设置需调用WebService接口需要传入的两个参数mobileCode、userId    
  76.             rpc.addProperty("mobileCode", params[0]);    
  77.             rpc.addProperty("userId", "");    
  78.         
  79.             // 生成调用WebService方法的SOAP请求信息,并指定SOAP的版本    
  80.             SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER12);    
  81.         
  82.             envelope.bodyOut = rpc;    
  83.             // 设置是否调用的是dotNet开发的WebService    
  84.             envelope.dotNet = true;    
  85.             // 等价于envelope.bodyOut = rpc;    
  86.             envelope.setOutputSoapObject(rpc);    
  87.         
  88.             HttpTransportSE transport = new HttpTransportSE(endPoint);    
  89.             try {    
  90.                 // 调用WebService    
  91.                 transport.call(soapAction, envelope);    
  92.             } catch (Exception e) {    
  93.                 e.printStackTrace();    
  94.             }    
  95.         
  96.             // 获取返回的数据    
  97.             SoapObject object = (SoapObject) envelope.bodyIn;    
  98.             // 获取返回的结果    
  99.             result = object.getProperty(0).toString();  
  100.             return result;  
  101.         }            
  102.           
  103.           
  104.         //(3)由doInBackground中的publishProgress(Progress...)触发onProgressUpdate这个方法  
  105.         @Override         
  106.         protected void onProgressUpdate(Integer... values) {        
  107.             // 更新进度              
  108.             tvLocation.setText("正在处理中……"+values[0]);      
  109.         }        
  110.                   
  111.         //(4)可以对后台任务的结果做出处理,结果就是doInBackground(Params...)的返回值。  
  112.         @Override       
  113.         protected void onPostExecute(String result) {      
  114.             // 返回HTML页面的内容                
  115.             tvLocation.setText(result);         
  116.         }    
  117.           
  118.     }     
  119. }  


四、配置文件
打开“AndroidManifest.xml”文件。

[html] view plain copy
 
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <manifest xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     package="com.genwoxue.webservice"  
  4.     android:versionCode="1"  
  5.     android:versionName="1.0" >  
  6.   
  7.     <uses-sdk  
  8.         android:minSdkVersion="10"  
  9.         android:targetSdkVersion="15" />  
  10.     <uses-permission android:name="android.permission.INTERNET"/>  
  11.     <application  
  12.         android:icon="@drawable/ic_launcher"  
  13.         android:label="@string/app_name" >  
  14.         <activity  
  15.             android:name=".MainActivity"  
  16.             android:label="@string/app_name" >  
  17.             <intent-filter>  
  18.                 <action android:name="android.intent.action.MAIN" />  
  19.                 <category android:name="android.intent.category.LAUNCHER" />  
  20.             </intent-filter>  
  21.         </activity>  
  22.     </application>  
  23.   
  24. </manifest>  

注意:由于是调用WebService,请注意在AndroidManifest.xml加上由于互联网权限。

 <uses-permission android:name="android.permission.INTERNET"/>

五、运行结果

相关TAG标签
上一篇:第102章、百度地图初探(从零开始学Android)
下一篇:走出这8个创业泥潭,离成功就不远了
相关文章
图文推荐

关于我们 | 联系我们 | 广告服务 | 投资合作 | 版权申明 | 在线帮助 | 网站地图 | 作品发布 | Vip技术培训 | 举报中心

版权所有: 红黑联盟--致力于做实用的IT技术学习网站