C#調用WebService樣本。

來源:互聯網
上載者:User
 C#調用WebService時和JS調用時有很多相似的地方,讓我們來一步一步實現:

  第一步:建立一個WebService

  這一步和JS調用WebService相同,在此不多說了。詳細可訪問如下地址:

  地址:<http://www.cnblogs.com/puresoul/archive/2010/08/19/1803567.html>

  第二步:建立一個頁面,實現C#調用Web服務

  在頁面上添加一個按鈕,後台代碼如下:

  代碼

  1 using System;

  2 using System.Collections.Generic;

  3 using System.Linq;

  4 using System.Web;

  5 using System.Web.UI;

  6 using System.Web.UI.WebControls;

  7

  8 using MSXML2;

  9

  10 public partial class Default4 : System.Web.UI.Page

  11 {

  12     protected void Page_Load(object sender, EventArgs e)

  13     {

  14

  15     }

  16     protected void Button1_Click(object sender, EventArgs e)

  17     {

  18         //Web服務的地址

  19          string URL = "http://localhost/YBWS/WebService.asmx";

  20

  21         //拼接資料

  22          string data;

  23         data = "<?xml version=\"1.0\" encoding=\"utf-8\"?>";

  24         data = data + "<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\">";

  25         data = data + "<soap12:Body>";

  26         data = data + "<HelloWorld xmlns=\"http://tempuri.org/\" />";

  27         data = data + "</soap12:Body>";

  28         data = data + "</soap12:Envelope>";

  29

  30         //建立非同步對象(XMLHTTP對象在MSXML2下)

  31         XMLHTTP xmlhttp = new XMLHTTP();

  32         xmlhttp.open("POST", URL, false, null, null);

  33         xmlhttp.setRequestHeader("Content-Type", "application/soap+xml");

  34         xmlhttp.send(data);

  35         Response.Write(System.Text.Encoding.UTF8.GetString((byte[])xmlhttp.responseBody));

  36         Response.End();

  37     }

  38 }

  39

  當點擊按鈕時,效果如:

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.