代码编写步骤
创建HttpTransportSE传输对象
创建SoapSerializationEnvelope对象(设定soap协议版本号)设置发送给服务器的数据bodyout属性
实例化SoapObject对象
设置调用方法的参数值,如果没有参数,可以省略
设置支付语言
调用HttpTransportSE对象的call()方法
获取服务器响应返回的SOAP消息(bodyin)
具体实现
public class WebServiceActivity extends Activity implements View.OnClickListener{
public final String TAG = getClass().getSimpleName();
EditText editText ;
Button button ;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.webservice);
initView();
}
private void initView(){
editText = (EditText) findViewById(R.id.edittext_webservice);
button = (Button) findViewById(R.id.btn_webservice);
button.setOnClickListener(this);
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btn_webservice:
getContent(editText.getText().toString().trim());
break;
}
}
// 查询手机号码归属地
private void getContent(final String content){
new Thread(new Runnable() {
@Override
public void run() {
if(!TextUtils.isEmpty(content)){
//定义方法名称
final String name = "GetMobileOwnership" ;
//定义命名空间
final String namespace = "http://www.36wu.com/";
//定义url
final String url = "http://web.36wu.com/MobileService.asmx?WSDL" ;
// namespace + name
final String soapAction = namespace + name ;
// 设置命名空间,及访问的方法名
SoapObject soapObject = new SoapObject(namespace,name);
soapObject.addProperty("mobile",content);
soapObject.addProperty("format","xml");
soapObject.addProperty("authkey","d117ac0e665848cd8162c3539a6ddef0");
// 创建 HttpTransportSE 对象
HttpTransportSE httpTransportSE = new HttpTransportSE(url);
// 创建 SoapSerializationEnvelope 对象
SoapSerializationEnvelope soapSerializationEnvelope = new SoapSerializationEnvelope(SoapSerializationEnvelope.VER11);
//支持 c# 语言
soapSerializationEnvelope.dotNet = true ;
// 把传递参数 放到 SoapSerializationEnvelope 对象里面
soapSerializationEnvelope.bodyOut = soapObject ;
try {
//发送请求
httpTransportSE.call(soapAction,soapSerializationEnvelope);
} catch (IOException e) {
e.printStackTrace();
} catch (XmlPullParserException e) {
e.printStackTrace();
}
//得到ws 返回的数据 (取数据)
SoapObject soapObjectResult = (SoapObject) soapSerializationEnvelope.bodyIn ;
Log.e(TAG,"soapObjectResult start " + soapObjectResult);
SoapObject getMobileOwnershipResult = (SoapObject) soapObjectResult.getProperty("GetMobileOwnershipResult") ;
SoapObject data = (SoapObject) getMobileOwnershipResult.getProperty("data") ;
Log.e(TAG,"soapObjectResult nor" + getMobileOwnershipResult);
Log.e(TAG,"soapObjectResult " + getMobileOwnershipResult);
Log.e(TAG,"soapObjectResult " + getMobileOwnershipResult.getProperty(0));
Log.e(TAG,"soapObjectResult " + getMobileOwnershipResult.getProperty(1));
Log.e(TAG,"soapObjectResult " + data.getProperty("corp"));
}
}
}).start();
}
}