用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

 

都是从别人的代码中拼凑出来,记下来备查

转载于:https://www.cnblogs.com/Tachikoma/archive/2010/07/13/1776872.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值