首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在Ruby中做XMLHttpRequest的最简单的方法?

在Ruby中做XMLHttpRequest的最简单的方法?
EN

Stack Overflow用户
提问于 2012-06-11 18:37:36
回答 3查看 2.1K关注 0票数 0

我想用Ruby语言写一篇XMLHttpRequest文章。我不想使用像Watir这样的框架。像Mechanize或Scrubyt这样的就可以了。我该怎么做呢?

EN

回答 3

Stack Overflow用户

发布于 2012-06-12 07:28:23

机械化:

代码语言:javascript
复制
require 'mechanize'
agent = Mechanize.new
agent.post 'http://www.example.com/', :foo => 'bar'
票数 2
EN

Stack Overflow用户

发布于 2015-10-16 03:28:49

使用'net/http‘的示例,(ruby 1.9.3):

你只需要在你的POST请求中为XMLHttpRequest添加一个额外的头(见下文)。

代码语言:javascript
复制
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
票数 2
EN

Stack Overflow用户

发布于 2012-06-11 18:43:46

XMLHTTPRequest是一个浏览器概念,但既然您问的是Ruby,那么我假设您想要做的就是从ruby脚本中模拟这样的请求?为此,有一个名为HTTParty的gem,它非常容易使用。

下面是一个简单的示例(假设您有gem -使用gem install httparty安装它):

代码语言:javascript
复制
require 'httparty'
response = HTTParty.get('http://twitter.com/statuses/public_timeline.json')
puts response.body, response.code, response.message, response.headers.inspect
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/10978533

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档