1

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

Community
  • 1
  • 1
Joel AZEMAR
  • 2,506
  • 25
  • 31

2 Answers2

5

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
WarHog
  • 8,622
  • 2
  • 29
  • 23
1

Ruby is not my field, but I have done something similar in C# recently. According to Ruby-Doc.org that method, .set_form_data sets the content type header to "application/x-www-form-urlencoded", which overrides you setting it to JSON.

A tool like Fiddler2 was great help in deciphering what was going on.

This questions answer has a link to a net:http JSON example https://stackoverflow.com/a/2037621/15710

Community
  • 1
  • 1
Mesh
  • 6,262
  • 5
  • 34
  • 53