我需要通过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代码中做错了吗?
答案 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\"}"