2012-06-11 113 views

回答

0

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 
+0

嗯,這很好,但我需要登錄到我需要提前刮取的網站,而HTTParty似乎沒有像機械化那樣容易。 – qendu

+3

@ user1223734好的,但如果這很重要,你應該在你的問題中提及它。 – Digitalex

2

機械化:

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

例與 '網/ HTTP',(紅寶石1.9.3 ):

您只需將XMLHttpRequest的附加頭添加到您的POST請求中(請參閱下文)。

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 

相關問題