最近的一个项目中调用webservice接口,需要验证soapheader,现将解决方法记录如下:(网上资料出处太多,就不做引用,原作者如看到,如有必要添加请通知)
1、先看接口
POST /webserver/ValideWebService.asmx HTTP/1.1 Host: IP地址 Content-Type: text/xml; charset=utf-8 Content-Length: length SOAPAction: "http://命名空间/Login" <?xml version="1.0" encoding="utf-8"?> <soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"> <soap:Header> <MySoapHeader xmlns="http://命名空间/"> <ProjectID>string</ProjectID> </MySoapHeader> </soap:Header> <soap:Body> <Login xmlns="http://命名空间/"> <loginName>string</loginName> <passowrd>string</passowrd> </Login> </soap:Body> </soap:Envelope>
验证时需要验证header和body两部分,需要引入第三方jar包,ksoap2-android-assembly-2.5.2-jar-with-dependencies.jar。下面就是我验证使用的方法,网上有许多,只不过无法验证,“拿来”修改一下,做个记录,供以后查看,也方便大家参阅。
先声明以下; //命名空间 private static final String NAMESPACE = "http://命名空间/"; //服务地址 private static String URL = "http://IP地址或者域名/webserver/ValideWebService.asmx"; //调用的方法名 private static final String METHOD_NAME = "Login"; //此处是命名空间+方法名 private static String SOAP_ACTION = "http://命名空间/Login"; private SoapObject detail;
由于2.3以上无法在主线程中直接访问网络,所以在需要的地方开启一个子线程,这里我在点击按钮登录的时候需要,因此写在onclick()方法下:
new Thread() { @Override public void run() { // TODO Auto-generated method stub super.run(); try { SoapObject rpc = new SoapObject(NAMESPACE, METHOD_NAME); //此处2个propertyinfo,是Login方法所需的参数,代码下面贴出asmx代码 PropertyInfo pi = new PropertyInfo(); pi.setName("loginName"); pi.setValue(cardNumStr); rpc.addProperty(pi); pi=new PropertyInfo(); pi.setName("passowrd"); pi.setValue(passwordStr); rpc.addProperty(pi); //soapheader在这里 Element[] header = new Element[1]; header[0] = new Element().createElement(NAMESPACE, "MySoapHeader"); Element username = new Element().createElement(NAMESPACE, "ProjectID"); username.addChild(Node.TEXT, "这里是值"); header[0].addChild(Node.ELEMENT, username); SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11); envelope.headerOut = header; envelope.bodyOut = rpc; envelope.dotNet = true; envelope.setOutputSoapObject(rpc); HttpTransportSE ht = new HttpTransportSE(URL); ht.call(SOAP_ACTION, envelope); //SoapObject detail =(SoapObject) envelope.getResponse(); System.out.println("返回的结果"+ detail.toString()); }catch (Exception e){ System.out.println("错误消息:"+ e.getMessage()); } Message msg = handler.obtainMessage(); msg.obj=detail; handler.sendMessage(msg); } }.start();
上面的cardNumStr和passwordStr是我从文本输入框获取的值。访问网络从接口通过验证然后获得返回值,对返回的数据进行处理就可以了。
用SoapObject,要不返回的detail为null。
private Handler handler = new Handler() { public void handleMessage(Message msg) { //这里做你的UI处理 }; };