虽然现在都是http的api,但是有些老项目依然用的是webservice,如果碰到了也需要用webservice来调用。所以像这种可能会用到的知识,花一秒钟搞懂概念就行,用到的时候再说。

webservice(SOAP)与HTTP接口的区别

什么是web service?

soap请求是HTTP POST的一个专用版本,遵循一种特殊的xml消息格式Content-type设置为: text/xml任何数据都可以xml化。

为什么要学习web service?

大多数对外接口会实现web service方法而不是http方法,如果你不会,那就没有办法对接。
web service相对http (post/get)有好处吗?

  1. 接口中实现的方法和要求参数一目了然
  2. 不用担心大小写问题
  3. 不用担心中文urlencode问题
  4. 代码中不用多次声明认证(账号,密码)参数
  5. 传递参数可以为数组,对象等…

web service相对http(post/get)快吗?

由于要进行xml解析,速度可能会有所降低。

web service 可以被http(post/get)替代吗?

完全可以,而且现在的开放平台都是用的HTTP(post/get)实现的。

SOAP 请求:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
POST /InStock HTTP/1.1
Host: www.example.org
Content-Type: application/soap+xml; charset=utf-8
Content-Length: nnn

<?xml version="1.0"?>
<soap:Envelope
xmlns:soap="http://www.w3.org/2001/12/soap-envelope"
soap:encodingStyle="http://www.w3.org/2001/12/soap-encoding">

<soap:Body xmlns:m="http://www.example.org/stock">
<m:GetStockPrice>
<m:StockName>IBM</m:StockName>
</m:GetStockPrice>
</soap:Body>

</soap:Envelope>

SOAP 响应:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
HTTP/1.1 200 OK
Content-Type: application/soap+xml; charset=utf-8
Content-Length: nnn

<?xml version="1.0"?>
<soap:Envelope
xmlns:soap="http://www.w3.org/2001/12/soap-envelope"
soap:encodingStyle="http://www.w3.org/2001/12/soap-encoding">

<soap:Body xmlns:m="http://www.example.org/stock">
<m:GetStockPriceResponse>
<m:Price>34.5</m:Price>
</m:GetStockPriceResponse>
</soap:Body>

</soap:Envelope>