通过KSoap三方插件解析WebService接口方法
话不多说,正文如下:
1.在lib中放入ksoap2的jar包并导入
2.在xml 配置文件中加入:
<!-- 访问网络的权限 --> <uses-permission android:name="android.permission.INTERNET" />
3.接下来就要通过代码调用借口了
//返回结果字符串是一个xml格式的,即对应的soap响应结果
private void getData() throws JSONException {
// 命名空间
String serviceNameSpace = “字符型”;
// 请求URL
String serviceURL = “字符型URL地址”;
// 调用的方法
String methodName = “调用的NameMethod";
String soapAction = serviceNameSpace + methodName;//命名空间+调用方法
// 实例化序列化的Envelop
SoapObject request = new SoapObject(serviceNameSpace(命名空间), methodName(调用方法名));
// 获得序列化的Envelop
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER12);//VER12 序列号和后台开发人员确定是多少
envelope.bodyOut = request;//有参数就加上参数 没有参数就不加了
// 设置是否调用的是dotNet开发的WebService
envelope.dotNet = true; //true是.net false是java
envelope.setOutputSoapObject(request);
// Android传输对象
HttpTransportSE transport = new HttpTransportSE(serviceURL);
transport.debug = true;
try {
transport.call(soapAction, envelope);
// 获取返回的数据
Object object = envelope.getResponse();
result = String.valueOf(object);
} catch (IOException e) {
e.toString();
} catch (XmlPullParserException e) {
e.printStackTrace();
}
}
下面是我自己分装的基于Ksoap工具类
/**
* @param url WebService服务器地址
* @param methodName WebService的调用方法名
* @param properties WebService的参数
*/
public String callwebService1POST(String url, final String methodName, HashMap<String, String> properties) {
// 实例化序列化的Envelop
SoapObject request = new SoapObject(Constant.NameSpace, methodName);
// 假设map是HashMap对象
// map中的key是String类型,value是Integer类型
String key , value;
if (properties != null) {
Iterator iter = properties.entrySet().iterator();
while (iter.hasNext()) {
Map.Entry entry = (Map.Entry) iter.next();
// 获取key
key = (String) entry.getKey();
// 获取value
value = (String) entry.getValue();
request.addProperty(key, value);
}
}
Log.e("测试-我就是看看数据:", request.toString());
// 获得序列化的Envelop
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
SoapEnvelope.VER12);
envelope.bodyOut = request;
// 设置是否调用的是dotNet开发的WebService
envelope.dotNet = true; //true是.net false是java
envelope.setOutputSoapObject(request);
// Android传输对象
HttpTransportSE transport = new HttpTransportSE(url);
transport.debug = true;
try {
transport.call(Constant.NameSpace + methodName, envelope);
// 获取返回的数据
Object object = envelope.getResponse();
String result = String.valueOf(object);
//Log.e("FactoryResult:", String.valueOf(object));
return result;
} catch (IOException e) {
e.toString();
} catch (XmlPullParserException e) {
e.printStackTrace();
}
return null;
}
在Activity中调用方法:
new Thread(new Runnable() {
@Override
public void run() {
webServiceUtils = new WebServiceUtils();
String result = webServiceUtils.callwebService1POST(WebService_url, MethodName, HashMap<String, String> properties)
try {
resoScanJSON(result);
} catch (JSONException e) {
e.printStackTrace();
}
}
}).start();
在这多说一嘴,就是必须在子线程中运行。