1

我需要通过 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

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​​ 代码做错了什么吗?

4

1 回答 1

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\"}"
于 2013-06-16T19:41:24.837 回答