我想用Ruby语言写一篇XMLHttpRequest文章。我不想使用像Watir这样的框架。像Mechanize或Scrubyt这样的就可以了。我该怎么做呢?
发布于 2012-06-12 07:28:23
机械化:
require 'mechanize'
agent = Mechanize.new
agent.post 'http://www.example.com/', :foo => 'bar'发布于 2015-10-16 03:28:49
使用'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发布于 2012-06-11 18:43:46
XMLHTTPRequest是一个浏览器概念,但既然您问的是Ruby,那么我假设您想要做的就是从ruby脚本中模拟这样的请求?为此,有一个名为HTTParty的gem,它非常容易使用。
下面是一个简单的示例(假设您有gem -使用gem install httparty安装它):
require 'httparty'
response = HTTParty.get('http://twitter.com/statuses/public_timeline.json')
puts response.body, response.code, response.message, response.headers.inspecthttps://stackoverflow.com/questions/10978533
复制相似问题