android通过web service调用查询手机归属地代码

1:本方法需要包点击下载 ksoap2-android-assembly-2.5.8-jar-with-dependencies.jar

2:在AndroidManifest.xml配置文件中添加<uses-permission android:name="android.permission.INTERNET"/>权限

3:核心代码

package com.main;

import java.io.IOException;

import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;
import org.xmlpull.v1.XmlPullParserException;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

public class MainActivity extends Activity {

EditText phone = null;
EditText set = null;
Button but = null;
// 命名空间
private static final String namespace = "http://WebXml.com.cn/";
// 调用方法(获得支持的城市)
private static final String getSupportCity = "getMobileCodeInfo";
// 请求URL
private static final String serviceUrl = "http://webservice.webxml.com.cn/WebServices/MobileCodeWS.asmx";

public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
phone = (EditText) findViewById(R.id.editText_phone);//传入的手机号码
set = (EditText) findViewById(R.id.editText_set);//返回值的显示空间
but = (Button) findViewById(R.id.but_tj);//提交按钮

but.setOnClickListener(new Button.OnClickListener() {

public void onClick(View v) {

String s = phone.getText().toString();
// 权限<uses-permission
// android:name="android.permission.INTERNET"/>
// 第一:实例化SoapObject
// 对象,指定webService的命名空间(从相关WSDL文档中可以查看命名空间),以及调用方法名称
SoapObject request = new SoapObject(namespace, getSupportCity);
// 第二步:假设方法有参数的话,设置调用方法参数
request.addProperty("mobileCode", s);
request.addProperty("userID", "");
// 第三步:设置SOAP请求信息(参数部分为SOAP协议版本号,与你要调用的webService中版本号一致):
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
SoapEnvelope.VER11);
// 调用dotnet设置
envelope.dotNet = true;
envelope.bodyOut = request;
// 第四步:注册Envelope,
// 第五步:构建传输对象,并指明WSDL文档URL
HttpTransportSE ht = new HttpTransportSE(serviceUrl);
// 第六步:调用WebService(其中参数为1:命名空间+方法名称,2:Envelope对象):
String soapAction = namespace + getSupportCity;
try {
ht.call(soapAction, envelope);
if (envelope.getResponse() != null) {
SoapObject sb = (SoapObject) envelope.bodyIn;
String ss = sb.getProperty(0).toString();
Log.v("tag", ss);

set.setText(ss);
} else {

Log.v("tga", "======else1");
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (XmlPullParserException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
}

里面都有注释说明,程序为最简单的webservice调用

 

posted @ 2011-11-07 16:46  左浪国  阅读(775)  评论(0编辑  收藏  举报