现在的位置: 首页 > 综合 > 正文

C#调用WebService示例。

2012年12月02日 ⁄ 综合 ⁄ 共 1559字 ⁄ 字号 评论关闭
 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

  当点击按钮时,效果如下图:

抱歉!评论已关闭.