上一章说的webservice访问封装成WebServiceUtils
代码思路:
工具类中的静态方法callWebService(String url, final String methodName,Map<String, String> properties,final WebServiceCallBack webServiceCallBack)就可以来获取我们想要的数据,现在讲解下里面的实现思路
- 方法说明:url为webservice服务端地址,methodName为方法名,properties为方法参数,有则遍历添加,webServiceCallBack为回调接口
- 使用了线程池来异步操作调用WebService接口,我们在线程中调用HttpTransportsSE对象的call(String soapAction, SoapEnvelope envelope)方法就能实现对WebService的调用,并且通过soapEnvelope.bodyIn获取WebService返回的信息
- 返回的信息是在子线程中,我们需要利用Handler来实现子线程与主线程进行转换,然后在Handler的handleMessage(Message msg)中将结果回调到接口webServiceCallBack.callBack的参数中
代码片段:
声明线程池
private static final ExecutorService executorService = Executors
.newFixedThreadPool(3);
静态访问方法
public static void callWebService(String url, final String methodName,
Map<String, String> properties,
final WebServiceCallBack webServiceCallBack) {
//创建httpTransportSE传输对象
final HttpTransportSE ht = new HttpTransportSE(url);
ht.debug = true;
//使用soap1.1协议创建Envelop对象
final SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
//实例化SoapObject对象
final SoapObject request = new SoapObject(Constant.SERVICE_NS, methodName);
/**
* 方法参数添加
* */
if (properties != null) {
for (Iterator<Map.Entry<String, String>> it = properties.entrySet()
.iterator(); it.hasNext();) {
Map.Entry<String, String> entry = it.next();
request.addProperty(entry.getKey(), entry.getValue());
}
}
// request.addProperty(methodName,properties);
//将SoapObject对象设置为SoapSerializationEnvelope对象的传出SOAP消息
envelope.bodyOut = request;
// 用于子线程与主线程通信的Handler
final Handler mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
// 将返回值回调到callBack的参数中
webServiceCallBack.callBack((SoapObject) msg.obj);
}
};
// 开启线程去访问WebService
executorService.submit(new Runnable() {
@Override
public void run() {
SoapObject resultSoapObject = null;
try{
//调用webService
ht.call(null, envelope);
if(envelope.getResponse() != null){
resultSoapObject = (SoapObject) envelope.bodyIn;
}
}catch (Exception e) {
e.printStackTrace();
}finally {
// 将获取的消息利用Handler发送到主线程
mHandler.sendMessage(mHandler.obtainMessage(0,
resultSoapObject));
}
}
});
}
回调接口
public interface WebServiceCallBack {
public void callBack(SoapObject result);
}
WebServiceUtils.callWebService(Constant.WEBSERVICE_URL, "sayHello", maps, new WebServiceUtils.WebServiceCallBack() {
//WebService接口返回的数据回调到这个方法中
@Override
public void callBack(SoapObject result) {
if(result != null){
String name = result.getProperty(0).toString();
System.out.println("==========================主线程返回值"+name);
// provinceList = parseSoapObject(result);
// mProvinceList.setAdapter(new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_list_item_1, provinceList));
}else{
System.out.println("==========================主线程无返回");
// Toast.makeText(MainActivity.this, "获取WebService数据错误", Toast.LENGTH_SHORT).show();
}
}
});