Android中Web Service学习(二)——Android调用Web Service实例

在上一篇文章Android中的Web Service学习(一)——Web Service介绍中已经介绍了Android中Web Service的基本概念,也对Web Service有了一个基本的了解,下面我们以实例来了解Android中如何调用Web Service。

实例:我们以查询手机号码的归属地Web Service为例
www.webxml.com.cn网站提供了手机号码归属地查询的Web Serivce,进入该网站中的手机号码归属地查询中,可以看到该Web Service的请求和响应示例。网站上分别提供了基于SOAP1.1和SOAP1.2协议的请求和响应示例,我们使用基SOAP1.2的。同时分别提供了使用POST和GET请求的请求和响应示例,我们以POST请求为例,下图就是手机号码归属地查询的基于SOAP1.2的Web Service的POST请求的请求和响应示例。
这里写图片描述

我们把请求示例中需要发送的XML数据保存到一个文件中放入Android项目的assets目录。,保存的时候< mobileCode >string< /mobileCode >中string替换成$mobile,因为发送请求的时候需要需要替换成输入的手机号码,因为免费用户userID为空,所以< userID >string < /userID >
直接变为< userID >< /userID>即可。
这里写图片描述

我们这里的例子调用Web Service服务的方式实际就上就是通过Http请求,发送相应的XML请求参数,然后解析返回的XML数据,我们这里的这种做法是不使用SOAP提供的相关请求方法,而是使用纯Http请求来调用Web Service,而在标准的开发过程中可能还需要使用SOAP的架包,使用SOAP架包中提供的请求Web Servcie的方法,和解析返回数据的方法来调用Web Servcie
请参考柳峰的
Android平台调用WebService详解
这篇文章来了解使用SOAP的提供相关方法来调用Web Service。

那么我们这里调用Web Service的流程是这样的,从asstes目录中的getMobileAddressService.xml文件中读取查询手机号码归属地这个Web Service请求时需要携带的请求数据,然后发送Http请求,响应的数据也是XML格式的,我们解析XML响应数据,得到手机号码归属地即可。

查询手机号码归属地Aandroid项目的主要代码如下:

布局文件 activity_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.android.webservice.test.MainActivity" >

    <EditText
        android:id="@+id/telEditText"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="请输入电话号码" />

    <Button
        android:id="@+id/queryTel"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/telEditText"
        android:text="查询归属地" >
    </Button>

    <TextView
        android:id="@+id/showAddressTv"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_below="@id/queryTel" >
    </TextView>

</RelativeLayout>

MainActivity的代码

public class MainActivity extends Activity implements OnClickListener {
    static final String TAG = "WebService";
    EditText telEditText;
    Button queryBtn;
    TextView showAddressTv;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
    }

    public void initView() {
        telEditText = (EditText) findViewById(R.id.telEditText);
        queryBtn = (Button) findViewById(R.id.queryTel);
        showAddressTv = (TextView) findViewById(R.id.showAddressTv);
        queryBtn.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        switch (v.getId()) {
        case R.id.queryTel:
            getAddress(telEditText.getText().toString());

            break;

        default:
            break;
        }
    }

    Handler handler = new Handler() {
        public void handleMessage(android.os.Message msg) {
            String address = (String) msg.obj;
            showAddressTv.setText(address);
        };

    };

    public void getAddress(final String mobile) {
        new Thread() {
            public void run() {
                String address = "";
                InputStream responseIs = null;
                OutputStream os = null;
                HttpURLConnection conn = null;
                URL url = null;
                try {
                    InputStream is = getAssets().open("getMobileAddressService.xml", Context.MODE_WORLD_READABLE);
                    String content = XMlTools.readXMLFile(is);
                    Log.i(TAG, content);
                    url = new URL("http://ws.webxml.com.cn/WebServices/MobileCodeWS.asmx");
                    conn = (HttpURLConnection) url.openConnection();
                    conn.setRequestProperty("Content-Type", "application/soap+xml");
                    conn.setRequestMethod("POST");
                    String s = content.replaceAll("\\$mobile", mobile);
                    os = conn.getOutputStream();
                    os.write(s.getBytes());
                    os.flush();
                    os.close();

                    System.out.println("---->" + "请求成功" + "," + s);
                    responseIs = conn.getInputStream();
                    XmlPullParser xmlPullParse = Xml.newPullParser();
                    xmlPullParse.setInput(responseIs, "utf-8");
                    int event = xmlPullParse.getEventType();
                    while (event != XmlPullParser.END_TAG) {

                        if (event == XmlPullParser.START_TAG) {
                            if (xmlPullParse.getName().equals("getMobileCodeInfoResult")) {
                                address = xmlPullParse.nextText();
                                Log.i(TAG, address);
                                Message msg = handler.obtainMessage();
                                msg.obj = address;
                                handler.sendMessage(msg);
                            }
                        }
                        event = xmlPullParse.next();
                    }

                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (XmlPullParserException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

            };

        }.start();

    }

}

MainActivity中使用到了一个XML工具类(XMLTools)中读取XML文件中数据的方法-readXMLFile(InputStream xmlIs),下面是这个XML工具类的编写:

public class XMlTools {
    public static String readXMLFile(InputStream xmlIs) {
        String content = "";
        BufferedReader br = null;
        br = new BufferedReader(new InputStreamReader(xmlIs));
        String line = "";
        try {
            while ((line = br.readLine()) != null) {
                content += line;
            }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return content;
        } finally {
            try {
                br.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                return content;
            }
        }
        return content;
    }


}

最后别忘了添加网络访问权限

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.android.webservice.test"
    android:versionCode="1"
    android:versionName="1.0" >

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

    <uses-sdk
        android:minSdkVersion="16"
        android:targetSdkVersion="19" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />                <category android:name="android.intent.category.LAUNCHER" />
 </intent-filter>
        </activity>
    </application>

</manifest>

运行结果

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值