標籤:style blog http color io os 使用 ar for
關於這個問題,如果使用百度都是前篇一律的代碼,好不容易上了google才找到完整的方法,這裡講所有的代碼都貼出來與大家分享。
首先是.NET寫的後台代碼
/// <summary> /// SoapHeader /// </summary> public class OwnSoapHeader:SoapHeader { public string UserName { get; set; } public string Password { get; set; } }/// <summary> /// WebService1 的摘要說明 /// </summary> [WebService(Namespace = "http://tempuri.org/")] [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] [System.ComponentModel.ToolboxItem(false)] // 若要允許使用 ASP.NET AJAX 從指令碼中調用此 Web 服務,請取消注釋以下行。 // [System.Web.Script.Services.ScriptService] public class WebService1 : System.Web.Services.WebService { public OwnSoapHeader OwnSoapHeader; [WebMethod] [SoapHeader("OwnSoapHeader")] public string Login() { if (OwnSoapHeader != null) { return OwnSoapHeader.UserName + "," + OwnSoapHeader.Password; } return "尚未登入"; } }
接下來是在瀏覽器中瀏覽查看我的介面,這裡面有很重要的資訊,包含了SoapHeader的名字以及參數
隨後就是使用Ksoap2調用我的介面了
private void DoLogin() { new Thread() { @Override public void run() { Looper.prepare(); // TODO Auto-generated method stub String sNameSpace = "http://tempuri.org/"; String sMethodName = "Login"; String sActionString = "http://tempuri.org/Login"; String sURL = "http://192.168.1.101:8088/WebService1.asmx"; SoapObject rpc = new SoapObject(sNameSpace, sMethodName); //在這裡加入了SoapHeader Element[] header = new Element[1];
//OwnSoapHeader與紅色標記處名字一致 header[0] = new Element().createElement(sNameSpace, "OwnSoapHeader ");
//UserName紅色標記處名字一致 Element username = new Element().createElement(sNameSpace, "UserName"); username.addChild(Node.TEXT, "admin"); header[0].addChild(Node.ELEMENT, username);
//Password紅色標記處名字一致 Element pass = new Element().createElement(sNameSpace, "Password"); pass.addChild(Node.TEXT, "123"); header[0].addChild(Node.ELEMENT, pass); SoapSerializationEnvelope envelope = new SoapSerializationEnvelope( SoapEnvelope.VER12); envelope.headerOut = header; envelope.bodyOut = rpc; envelope.dotNet = true; envelope.setOutputSoapObject(rpc); HttpTransportSE ht = new HttpTransportSE(sURL); SoapObject soapObject = null; try { ht.call(sActionString, envelope); soapObject = (SoapObject) envelope.bodyIn; } catch (IOException ex) { // TODO Auto-generated catch block ex.printStackTrace(); } catch (XmlPullParserException ex) { // TODO Auto-generated catch block ex.printStackTrace(); } Bundle result = new Bundle(); if (soapObject != null) { result.putString("result", soapObject.toString()); } else { result.putString("result", sURL); } Message msg = new Message(); msg.setData(result); msg.what = 1; handler.handleMessage(msg); Looper.loop(); } }.start(); } Handler handler = new Handler() { @Override public void handleMessage(Message msg) { // TODO Auto-generated method stub if (msg.what == 1) { Bundle result = msg.getData(); String text = result.getString("result"); Toast.makeText(MainActivity.this, text, Toast.LENGTH_LONG) .show(); } } };
至此已經全部OK了,能夠接收到服務端回傳的使用者資料
使用Ksoap2調用Web Service加入SoapHeader