用Ruby实现 Web Service Server ,并用Ruby发送 HTTP请求 Web Service
因为项目需要,搭建一个最简单的web service Server,并用Ruby发送HTTP请求 Web Service
1. 首先先搭建一个Server , 实现一个简单的加法
require 'soap/rpc/standaloneServer' class AddClass def add(i,j) return i.to_i + j.to_i end end class AddServer < SOAP::RPC::StandaloneServer def on_init add = AddClass.new add_method(add , 'add' , 'a' , 'b') end end server = AddServer.new('hello' , 'namespace' , '0.0.0.0' , 2000) trap('INT'){ server.shutdown } server.level=SOAP::RPC::StandaloneServer::DEBUG server.start
web service 名空间为namespace,地址为 localhost:2000,并输出DEBUG级别的信息
2. 用Ruby,发送HTTP POST请求,调用Web service
require 'net/http' require 'uri' req_headers= { 'Content-Type' => 'text/xml; charset=utf-8', 'SOAPAction' => '"http://localhost:2000/add#add"', } req_body = <<EOF <?xml version="1.0" encoding="utf-8"?> <soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"> <soap:Body> <add xmlns="namespace"> <i>100</i> <j>1</j> </add> </soap:Body> </soap:Envelope> EOF http = Net::HTTP.new('localhost' , 2000) http.set_debug_output $stdout res = http.request_post("/add" , req_body , req_headers) puts res.body
很简单,就是手动制造出 HTTP POST请求Header 和 Body,Body中为请求的xml
都是从别人的代码中拼凑出来,记下来备查