06 Web服务 - WebService

1. 传统的Web服务

Web service也叫XML Web Service, 它通过标准化接口(WSDL)提供,使用标准化语言(XML)进行描述,并可基于标准化传输方式(HTTP和JMS)、采用标准化 协议(SOAP)进行调用,并使用XML SCHEMA方式对数据进行描述,它有什么好处呢?

第一,Web Service是跨平台的,应用程序经常需要从运行在IBM主机上的程序中获取数据,然后把数据发送到主机或UNIX应用程序中去。即使在同一个平台上, 不同软件厂商生产的各种软件也常常需要集成起来。通过WebService,应用程序可以用标准的方法把功能和数据“暴露”出来,供其它应用程序使用。
第二,Web Service是无语言限制的,你可以使用.NET,JAVA,PHP,VB......等多种语言开发并进行相互调用。
第三, 使用SOAP时数据是以ASCII文本的方式传输,调用很方便,数据容易通过防火墙而实现无缝连接。

 

2. Web服务优缺点

优点(适用的场景)
  1、跨防火墙的通信
  2、跨平台,跨语言应用程序集成
  3、软件和数据重用
缺点(不适用的场景)
  1、 单机应用程序
  2、 局域网的一些应用程序

 

3. Web服务的实现

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
 
namespace WebServiceSoap
{
    public class Service1 : System.Web.Services.WebService
    {
        [WebMethod]
        public string HelloWorld()
        {
            return "Hello World";
        }
    }
}

 

4. 用JS调用Web Service的例子

//这是我们创建的Web服务的地址
var URL = “http://localhost/YBWS/WebService.asmx”;
//在这处拼接Http请求内容
var data; data = '<?xml version="1.0" encoding="utf-8"?>';
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">';
data = data + '<soap12:Body>';
data = data + '<HelloWorld xmlns="http://tempuri.org/" />';
data = data + '</soap12:Body>'; data = data + '</soap12:Envelope>';
//创建异步对象
var xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
xmlhttp.Open("POST", URL, false);
xmlhttp.SetRequestHeader("Content-Type", "application/soap+xml");
xmlhttp.Send(data);

 

5. 对Web服务的Http请求

POST http://22.11.143.88:9003/Service1.asmx HTTP/1.1
Host: 22.11.143.88:9003
Content-Type: application/soap+xml; charset=utf-8
Content-Length: 314
 
<?xml version="1.0" encoding="utf-8"?>
<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">
  <soap12:Body>
    <HelloWorld xmlns="http://tempuri.org/" />
  </soap12:Body>
</soap12:Envelope>

 

6. 对Web服务的Http响应

HTTP/1.1 200 OK
Cache-Control: private, max-age=0
Content-Type: application/soap+xml; charset=utf-8
Server: Microsoft-IIS/8.5
X-AspNet-Version: 2.0.50727
X-Powered-By: ASP.NET
Date: Mon, 08 Dec 2014 02:15:12 GMT
Content-Length: 361
 
<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <soap:Body>
    <HelloWorldResponse xmlns="http://tempuri.org/">
      <HelloWorldResult>Hello World</HelloWorldResult>
    </HelloWorldResponse>
  </soap:Body>
</soap:Envelope>

 

posted @   紫色物语  阅读(175)  评论(0编辑  收藏  举报
努力加载评论中...
点击右上角即可分享
微信分享提示