Manualy完美卷曲工作:
curl https://www.googleapis.com/urlshortener/v1/url \
-H 'Content-Type: application/json' \
-d '{"longUrl": "http://www.rubyinside.com/"}'
当我尝试在Net :: Http:
中创建它时require "net/https"
require "uri"
uri = URI.parse("https://www.googleapis.com/urlshortener/v1/url")
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true
http.verify_mode = OpenSSL::SSL::VERIFY_NONE
request = Net::HTTP::Post.new(uri.path)
request["Content-Type"] = "application/json"
request.set_form_data({"longUrl" => "http://www.rubyinside.com/"})
response = http.request(request)
puts response.body
但是回复失败了:
{
"error": {
"errors": [
{
"domain": "global",
"reason": "parseError",
"message": "This API does not support parsing form-encoded input."
}
],
"code": 400,
"message": "This API does not support parsing form-encoded input."
}
}
=> nil
答案 0 :(得分:5)
您必须以json的形式发送数据,而不是按照您尝试的方式编码。尝试更改您的代码:
....
require 'json'
....
request.body = {"longUrl" => "http://www.rubyinside.com/"}.to_json
答案 1 :(得分:1)
Ruby不是我的领域,但我最近在C#中做过类似的事情。根据Ruby-Doc.org的方法,.set_form_data将内容类型标题设置为“application / x-www-form-urlencoded”,这将覆盖您将其设置为JSON。
像Fiddler2这样的工具在破译正在发生的事情方面提供了很大的帮助。
这个问题的答案有一个网络链接:http JSON示例https://stackoverflow.com/a/2037621/15710