rubynet-httpgoo.gl

How set Header with Net::Http for Goo.gl Shorten service?


Like describe in API Goo.gl

Manualy curl work perfectly :

curl https://www.googleapis.com/urlshortener/v1/url \
    -H 'Content-Type: application/json' \
    -d '{"longUrl": "http://www.rubyinside.com/"}'

Bu when i try to make this in 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

But fail with the response :

{
 "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


Solution

  • You have to send your data as json, not form encoded as you are trying to do. Try to change your code like so:

    ....
    require 'json'
    
    ....
    request.body = {"longUrl" => "http://www.rubyinside.com/"}.to_json