在Ruby中执行XMLHttpRequest的最简单方法是什么?

时间:2012-06-11 10:37:36

标签: ruby screen-scraping

我想在Ruby中执行XMLHttpRequest POST。我不想使用像Watir这样的框架。像Mechanize或Scrubyt这样的东西会很好。我怎么能这样做?

3 个答案:

答案 0 :(得分:2)

机械化:

require 'mechanize'
agent = Mechanize.new
agent.post 'http://www.example.com/', :foo => 'bar'

答案 1 :(得分:1)

XMLHTTPRequest是一个浏览器概念,但既然你在询问Ruby,我认为你想要做的就是从ruby脚本模拟这样的请求?为此,有一个名为HTTParty的宝石很容易使用。

这是一个简单的例子(假设你有宝石 - 用gem install httparty安装):

require 'httparty'
response = HTTParty.get('http://twitter.com/statuses/public_timeline.json')
puts response.body, response.code, response.message, response.headers.inspect

答案 2 :(得分:1)

'net / http'示例,(ruby 1.9.3):

您只需要为您的POST请求添加XMLHttpRequest的额外标头(见下文)。

require 'net/http'
require 'uri'  # convenient for using parts of an URI

uri = URI.parse('http://server.com/path/to/resource')

# create a Net::HTTP object (the client with details of the server):
http_client = Net::HTTP.new(uri.host, uri.port)

# create a POST-object for the request:
your_post = Net::HTTP::Post.new(uri.path)

# the content (body) of your post-request:
your_post.body = 'your content'

# the headers for your post-request (you have to analyze before,
# which headers are mandatory for your request); for example:
your_post['Content-Type'] = 'put here the content-type'
your_post['Content-Length'] = your_post.body.size.to_s
# ...
# for an XMLHttpRequest you need (for example?) such header:
your_post['X-Requested-With'] = 'XMLHttpRequest'

# send the request to the server:
response = http_client.request(your_post)

# the body of the response:
puts response.body