ruby中的POST请求 - 来自python

时间:2013-06-16 19:20:39

标签: ruby post net-http

我需要通过ruby脚本发送一些POST数据。我已经能够使用requests通过python发送它,代码如下:

payload = {"firstName": "John", "lastName": "Appleseed"}
headers = {'content-type': 'application/json'}
r = requests.post ("http://localhost:8000/api/v1/person/?format=json",data=json.dumps(payload), headers = headers)

现在,我尝试使用net/http将其翻译成ruby:

url = "http://localhost:8000/api/v1/person/?format=json"
payload = {:firstName => 'John', :lastName => 'Appleseed'}.to_s

request = Net::HTTP::Post.new(url)
request.add_field('content-type', 'application/json')
request.body = payload

uri = URI.parse(url)
http = Net::HTTP.new(uri.host, uri.port)
response = http.request(request)

但是我从服务器上获得了404。知道我可能在ruby代码中做错了吗?

1 个答案:

答案 0 :(得分:1)

看看payload的样子:

>> {:firstName => 'John', :lastName => 'Appleseed'}.to_s
=> "firstNameJohnlastNameAppleseed"

json.dumps不会产生该输出。您想要使用to_json代替:

>> require "json"
=> true
>> {:firstName => 'John', :lastName => 'Appleseed'}.to_json
=> "{\"firstName\":\"John\",\"lastName\":\"Appleseed\"}"