POST json数据和自定义标头

时间:2012-04-18 05:30:53

标签: ruby curl

我有以下ruby代码,我尝试以与此curl相同的方式实现。

curl -X POST \
  -H "X-Parse-Application-Id: $APP_ID" \
  -H "X-Parse-REST-API-Key: $KEY" \
  -H "Content-Type: application/json" \
  -d '{"score": 1337, "playerName": "Sean Plott", "cheatMode": false }' \
  https://api.parse.com/1/classes/GameScore

这是红宝石代码:

def execute_post
  puts "executing post script.."
  payload ={
    "score" => "1337",
    "playerName" => "Sean Plott", 
    "cheatMode" => "false"

  }.to_json
  headers = {
    'X-Parse-Application-Id' => $APP_ID, 
    'X-Parse-REST-API-KEY' => $KEY,
    'Content-Type' => 'application/json'
  }
  url = "https://" + $DOMAIN + $BASE_URL + $LIST_CLASS
  uri = URI.parse(url)
  puts uri
  puts payload

  puts "***************"
  req = Net::HTTP::Post.new(uri.host, initheader = headers)
  req.body = payload
  response = Net::HTTP.new(uri.host, uri.port).start{|http| http.request(req)}

  puts "Response #{response.code} #{response.message}: #{response.body}"

end

出于某种原因,我收到了错误消息。关于出了什么问题的任何想法?

/System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/lib/ruby/1.8/net/protocol.rb:135:in `sysread': end of file reached (EOFError)
    from /System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/lib/ruby/1.8/net/protocol.rb:135:in `rbuf_fill'
    from /System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/lib/ruby/1.8/timeout.rb:62:in `timeout'
    from /System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/lib/ruby/1.8/timeout.rb:93:in `timeout'
    from /System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/lib/ruby/1.8/net/protocol.rb:134:in `rbuf_fill'
    from /System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/lib/ruby/1.8/net/protocol.rb:116:in `readuntil'
    from /System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/lib/ruby/1.8/net/protocol.rb:126:in `readline'
    from /System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/lib/ruby/1.8/net/http.rb:2024:in `read_status_line'
    from /System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/lib/ruby/1.8/net/http.rb:2013:in `read_new'
    from /System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/lib/ruby/1.8/net/http.rb:1050:in `request'
    from parse_connect.rb:33:in `execute_post'
    from /System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/lib/ruby/1.8/net/http.rb:543:in `start'
    from parse_connect.rb:33:in `execute_post'
    from parse_connect.rb:42

2 个答案:

答案 0 :(得分:1)

尝试这样:

require 'mechanize'
Mechanize.new.post url, data.to_json, headers

如果不起作用,请运行fiddler并尝试这样:

Mechanize.new{|a| a.set_proxy 'localhost', 8888}.post url, data.to_json, headers

然后在fiddler中检查请求

答案 1 :(得分:0)

在您的curl示例中,您使用的是HTTPS。

使用Net :: HTTP时,您需要专门启用HTTPS(仅在您的URL中放置https://是不够的。)

http =  Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true
response = http.start{|http| http.request(req)}