Like describe in API Goo.gl
手动卷曲完美:
curl https://www.googleapis.com/urlshortener/v1/url \
-H 'Content-Type: application/json' \
-d '{"longUrl": "http://www.rubyinside.com/"}'
Bu当我尝试在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
I see an another issue but seem does not work
This httparty sample code work but i want use net_http
最佳答案
您必须以json的形式发送数据,而不是像您尝试的那样以表单编码的形式发送数据尝试像这样更改代码:
....
require 'json'
....
request.body = {"longUrl" => "http://www.rubyinside.com/"}.to_json
关于ruby - 如何通过Net::Http设置Header以实现Goo.gl缩短服务?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/8386653/