vb調用webservice(二)

利用SOAP協議

首先,需要引用 microsoft xml 6.0

在客戶端調用時

'定義soap消息 這個消息可以在webservice調用過程獲得。主要處理在soap12:Body
   Dim strtest As String


'    strtest = "<?xml version=""1.0"" encoding=""utf-8""?> "
'    strtest = strtest + " <soap12:Envelope xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xmlns:xsd=""http://www.w3.org/2001/XMLSchema"" xmlns:soap12=""http://www.w3.org/2003/05/soap-envelope""> "
'    strtest = strtest + " <soap12:Body> "
'    strtest = strtest + " <HelloWorld xmlns=""http://tempuri.org/""> "
'    strtest = strtest + " <str>" + str + "</str> "
'    strtest = strtest + " </HelloWorld> "
'    strtest = strtest + " </soap12:Body> "
'    strtest = strtest + " </soap12:Envelope> "
    strtest = "<?xml version=""1.0"" encoding=""utf-8""?> "
    strtest = strtest + " <soap12:Envelope xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xmlns:xsd=""http://www.w3.org/2001/XMLSchema"" xmlns:soap12=""http://www.w3.org/2003/05/soap-envelope""> "
    strtest = strtest + " <soap12:Body> "
    strtest = strtest + " <returnclasstest xmlns=""http://tempuri.org/"" /> "
    strtest = strtest + " </soap12:Body> "
    strtest = strtest + " </soap12:Envelope> "
    strxml = strtest

    '定義一個http對象,一邊向服務器發送post消息
    Dim h As MSXML2.ServerXMLHTTP40
    '定義一個XML的文檔對象,將手寫的或者接受的XML內容轉換成XML對象
    Dim x As MSXML2.DOMDocument40
    '初始化XML對象
    Set x = New MSXML2.DOMDocument40
    '將手寫的SOAP字符串轉換爲XML對象
    x.loadXML strxml
    '初始化http對象
    Set h = New MSXML2.ServerXMLHTTP40
    '向指定的URL發送Post消息。這裏的webservice地址爲需要引用的地址
    h.open "POST", "http://localhost/webserice/Service.asmx", False
    h.setRequestHeader "Content-Type", "text/xml"
    h.send (strxml)
    While h.readyState <> 4
    Wend
    '顯示返回的XML信息
    Text1.Text = h.responseText

至此,獲得webservice返回消息成功   webservice返回值可以爲自定義類
在VB6.0 vs2005下調試成功

下附webservice源碼:

using System;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;

[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
public class Service : System.Web.Services.WebService
{
    public Service () {

        //如果使用設計的組件,請取消註釋以下行
        //InitializeComponent();
    }

    [WebMethod]
    public string HelloWorld(string str) {
        return "Hello World :" + str;
    }
    [WebMethod]
    public int add(int i, int j)
    {
        return i + j;
    }
    [WebMethod]
    public returnclass returnclasstest()
    {
        returnclass r = new returnclass();
        r.ID = "IDtest";
        r.NAME ="NAMEtest";
        return r;
    }
}
public class returnclass
{
    public returnclass()
    { }
    private string id;
    private string name;
    public string ID
    {
        get { return id; }
        set { id = value; }
    }
    public string NAME
    {
        get { return name; }
        set { name = value; }
    }
}

發佈了28 篇原創文章 · 獲贊 6 · 訪問量 25萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章