android调用WebService接口

[来源] 达内    [编辑] 达内   [时间]2012-09-18

一个电话号码在线查询的简单例子,android调用webService接口

01
package com.example.webservice;
02

03
import org.ksoap2.SoapEnvelope;
04
import org.ksoap2.serialization.SoapObject;
05
import org.ksoap2.serialization.SoapSerializationEnvelope;
06
import org.ksoap2.transport.HttpTransportSE;
07

08
import android.app.Activity;
09
import android.os.Bundle;
10
import android.view.View;
11
import android.view.View.OnClickListener;
12
import android.widget.Button;
13
import android.widget.EditText;
14
import android.widget.TextView;
15

16
public class MainActivity extends Activity {
17
private EditText phoneSecEditText;
18
private TextView resultView;
19
private Button queryButton;
20

21
@Override
22
public void onCreate(Bundle savedInstanceState) {
23
super.onCreate(savedInstanceState);
24
setContentView(R.layout.activity_main);
25

26
phoneSecEditText = (EditText) findViewById(R.id.phone_sec);
27
resultView = (TextView) findViewById(R.id.result_text);
28
queryButton = (Button) findViewById(R.id.query_btn);
29

30
queryButton.setOnClickListener(new OnClickListener() {
31
@Override
32
public void onClick(View v) {
33
// 手机号码(段)
34
String phoneSec = phoneSecEditText.getText().toString().trim();
35
// 简单判断用户输入的手机号码(段)是否合法
36
if ("".equals(phoneSec) || phoneSec.length() < 7) {
37
// 给出错误提示
38
phoneSecEditText.setError("您输入的手机号码(段)有误!");
39
phoneSecEditText.requestFocus();
40
// 将显示查询结果的TextView清空
41
resultView.setText("");
42
return;
43
}
44
// 查询手机号码(段)信息
45
getRemoteInfo(phoneSec);
46
}
47
});
48
}
49

50
/**
51
* 手机号段归属地查询
52
*
53
* @param phoneSec
54
* 手机号段
55
*/
56
public void getRemoteInfo(String phoneSec) {
57
// 命名空间
58
String nameSpace = "http://WebXml.com.cn/";
59
// 调用的方法名称
60
String methodName = "getMobileCodeInfo";
61
// EndPoint
62
String endPoint = "http://webservice.webxml.com.cn/WebServices/MobileCodeWS.asmx";
63
// SOAP Action
64
String soapAction = "http://WebXml.com.cn/getMobileCodeInfo";
65

66
// 指定WebService的命名空间和调用的方法名
67
SoapObject rpc = new SoapObject(nameSpace, methodName);
68

69
// 设置需调用WebService接口需要传入的两个参数mobileCode、userId
70
rpc.addProperty("mobileCode", phoneSec);
71
rpc.addProperty("userId", "");
72

73
// 生成调用WebService方法的SOAP请求信息,并指定SOAP的版本
74
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
75
SoapEnvelope.VER10);
76

77
envelope.bodyOut = rpc;
78
// 设置是否调用的是dotNet开发的WebService
79
envelope.dotNet = true;
80
// 等价于envelope.bodyOut = rpc;
81
envelope.setOutputSoapObject(rpc);
82

83
HttpTransportSE transport = new HttpTransportSE(endPoint);
84
try {
85
// 调用WebService
86
transport.call(soapAction, envelope);
87
} catch (Exception e) {
88
e.printStackTrace();
89
}
90

91
// 获取返回的数据
92
SoapObject object = (SoapObject) envelope.bodyIn;
93
// 获取返回的结果
94
String result = object.getProperty(0).toString();
95

96
// 将WebService返回的结果显示在TextView中
97
resultView.setText(result);
98
}
99
}

 

资源下载