在Android中调用WebService

来源:互联网 发布:php函数插件 编辑:程序博客网 时间:2024/04/30 12:16
 某些情况下我们可能需要与Mysql或者Oracle数据库进行数据交互,有些朋友的第一反应就是直接在Android中加载驱动然后进行数据的增删改查。我个人不推荐这种做法,一是手机毕竟不是电脑,操作大量数据费时费电;二是流量贵如金那。我个人比较推荐的做法是使用Java或PHP等开发接口或者编写WebService进行数据库的增删该查,然后Android调用接口或者WebService进行数据的交互。本文就给大家讲解在Android中如何调用远程服务器端提供的WebService。
既然是调用WebService,我们首先的搭建WebService服务器。为了便于操作,我们就使用网上免费的WebService进行学习。
地址:http://www.webxml.com.cn/zh_cn/index.aspx
下面演示的就是如何通过该网站提供的手机号码归属地查询WebService服务查询号码归属地
调用地址http://webservice.webxml.com.cn/WebServices/MobileCodeWS.asmx?op=getMobileCodeInfo。
首先,将请求消息保存在XML文件中,然后使用$替换请求参数,如下:
mobilesoap.xml
<SPANstyle="FONT-SIZE: 16px"><?xmlversion="1.0"encoding="utf-8"?>
<soap12:Envelopexmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns:xsd="http://www.w3.org/2001/XMLSchema"xmlns:soap12="http://www.w3.org/2003/05/soap-envelope">
  <soap12:Body>
    <getMobileCodeInfoxmlns="http://WebXml.com.cn/">
      <mobileCode>$mobile</mobileCode>
      <userID></userID>
    </getMobileCodeInfo>
  </soap12:Body>
</soap12:Envelope></SPAN>
其次,设计MainActivity布局文件,
main.xml
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
<SPANstyle="FONT-SIZE: 16px"><?xmlversion="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">
    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="手机号码"/>
    <EditText
        android:id="@+id/mobileNum" 
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text=""
        />
    <Button
        android:id="@+id/btnSearch"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="查询"
        />
    <TextView
        android:id="@+id/mobileAddress"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        />
</LinearLayout></SPAN>
下面贴出MainActivity,
在Android中调用WebService还是比较简单的:请求webservice,获取服务响应的数据,解析后并显示。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
<SPAN style="FONT-SIZE: 16px">packagecom.szy.webservice;
  
  
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
  
  
import org.xmlpull.v1.XmlPullParser;
  
  
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.util.Xml;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
  
  
/**
 * @author coolszy
 * @date 2012-3-8
 * @bloghttp://blog.92coding.com
 */
public class MainActivity extendsActivity
{
    privateEditText mobileNum;
    privateTextView mobileAddress;
    privatestatic final String TAG = "MainActivity";
  
  
    @Override
    publicvoid onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
  
  
        mobileNum = (EditText)this.findViewById(R.id.mobileNum);
        mobileAddress = (TextView)this.findViewById(R.id.mobileAddress);
        Button btnSearch = (Button)this.findViewById(R.id.btnSearch);
        btnSearch.setOnClickListener(newView.OnClickListener()
        {
            @Override
            publicvoid onClick(View v)
            {
                // 获取电话号码
                String mobile = mobileNum.getText().toString();
                // 读取xml文件
                InputStream inStream =this.getClass().getClassLoader().getResourceAsStream("mobilesoap.xml");
                try
                {
                    // 显示电话号码地理位置,该段代码不合理,仅供参考
                    mobileAddress.setText(getMobileAddress(inStream, mobile));
                }catch (Exception e)
                {
                    Log.e(TAG, e.toString());
                    Toast.makeText(MainActivity.this,"查询失败", 1).show();
                }
            }
        });
    }
  
  
    /**
     * 获取电话号码地理位置
     
     * @param inStream
     * @param mobile
     * @return
     * @throws Exception
     */
    privateString getMobileAddress(InputStream inStream, String mobile)throws Exception
    {
        // 替换xml文件中的电话号码
        String soap = readSoapFile(inStream, mobile);
        byte[] data = soap.getBytes();
        // 提交Post请求
        URL url =new URL("http://webservice.webxml.com.cn/WebServices/MobileCodeWS.asmx");
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("POST");
        conn.setConnectTimeout(5* 1000);
        conn.setDoOutput(true);
        conn.setRequestProperty("Content-Type","application/soap+xml; charset=utf-8");
        conn.setRequestProperty("Content-Length", String.valueOf(data.length));
        OutputStream outStream = conn.getOutputStream();
        outStream.write(data);
        outStream.flush();
        outStream.close();
        if(conn.getResponseCode() == 200)
        {
            // 解析返回信息
            returnparseResponseXML(conn.getInputStream());
        }
        return"Error";
    }
  
  
    privateString readSoapFile(InputStream inStream, String mobile)throws Exception
    {
        // 从流中获取文件信息
        byte[] data = readInputStream(inStream);
        String soapxml =new String(data);
        // 占位符参数
        Map<String, String> params =new HashMap<String, String>();
        params.put("mobile", mobile);
        // 替换文件中占位符
        returnreplace(soapxml, params);
    }
  
  
    /**
     * 读取流信息
     
     * @param inputStream
     * @return
     * @throws Exception
     */
    privatebyte[] readInputStream(InputStream inputStream)throws Exception
    {
        byte[] buffer =new byte[1024];
        intlen = -1;
        ByteArrayOutputStream outSteam =new ByteArrayOutputStream();
        while((len = inputStream.read(buffer)) != -1)
        {
            outSteam.write(buffer,0, len);
        }
        outSteam.close();
        inputStream.close();
        returnoutSteam.toByteArray();
    }
  
  
    /**
     * 替换文件中占位符
     
     * @param xml
     * @param params
     * @return
     * @throws Exception
     */
    privateString replace(String xml, Map<String, String> params) throws Exception
    {
        String result = xml;
        if(params != null&& !params.isEmpty())
        {
            for(Map.Entry<String, String> entry : params.entrySet())
            {
                String name ="\\$" + entry.getKey();
                Pattern pattern = Pattern.compile(name);
                Matcher matcher = pattern.matcher(result);
                if(matcher.find())
                {
                    result = matcher.replaceAll(entry.getValue());
                }
            }
        }
        returnresult;
    }
  
  
    /**
     * 解析XML文件
     * @param inStream
     * @return
     * @throws Exception
     */
    privatestatic String parseResponseXML(InputStream inStream)throws Exception
    {
        XmlPullParser parser = Xml.newPullParser();
        parser.setInput(inStream,"UTF-8");
        inteventType = parser.getEventType();// 产生第一个事件
        while(eventType != XmlPullParser.END_DOCUMENT)
        {
            // 只要不是文档结束事件
            switch(eventType)
            {
            caseXmlPullParser.START_TAG:
                String name = parser.getName();// 获取解析器当前指向的元素的名称
                if("getMobileCodeInfoResult".equals(name))
                {
                    returnparser.nextText();
                }
                break;
            }
            eventType = parser.next();
        }
        returnnull;
    }
}</SPAN>
最后注意,由于需要访问网络,需要加上权限
1
<SPANstyle="FONT-SIZE: 16px"><uses-permissionandroid:name="android.permission.INTERNET"/></SPAN>

通过上面简单的例子,相信大家已经学习了如何在Android中调用WebService,最后运行效果:



实例代码:http://115.com/file/anjh65a6

原创粉丝点击