0

Ruby で XMLHttpRequest POST を実行したいと考えています。Watir のようなフレームワークは使いたくありません。Mechanize や Scrubyt などで問題ありません。これどうやってするの?

4

3 に答える 3

2

機械化:

require 'mechanize'
agent = Mechanize.new
agent.post 'http://www.example.com/', :foo => 'bar'
于 2012-06-11T23:28:23.437 に答える
2

「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

于 2015-10-15T19:28:49.107 に答える
1

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.inspect
于 2012-06-11T10:43:45.503 に答える