3

I have a post request with headers and query parameters that I want to fire with net/http. The request returns 200 but the response body says: {\"error\":\"invalid_request\",\"error_description\":\"Required query parameter 'grant_type' missing.\"}

This is the complete function I call:

def Search.request_oauth_access_token
    require 'net/http'
    uri = URI.parse('https://request.url/oauth2/access_token')
    params = {
        'grant_type' => 'my:grant:type'
    }
    headers = {
    'Authorization' => 'Basic sldhfgKGsdfgGOI23==',
    'Content-Type' => 'application/x-www-form-urlencoded'
    }
    http = Net::HTTP.new(uri.host, uri.port)
    http.use_ssl = true
    request = Net::HTTP::Post.new(uri.request_uri, headers)
    query = URI.encode_www_form_component(params)
    request.body = query
    response = http.request(request)
    p response.body
end

I am using Rails 5.0.2.

3 Answers3

3

Solved it. Turned out that I had a syntax error in the params definition. This was the correct way of defining it:

params = {
        grant_type: 'my:grant:type'
    }

And then in the request:

query = URI.encode_www_form(params)
http.request(request, query)
1

The simplest way is using ruby core library:

require "uri"
require "net/http"

params = {
          'field1' => 'Nothing is less important',
          'field2' => 'Submit'
}
x = Net::HTTP.post_form(URI.parse('http://www.yahoo.com/web/ch05/formpost.asp'), params)
puts x.body

This saved my day

Kumar KS
  • 873
  • 10
  • 21
0

You can also change your params syntax to the following:

params = [ [ "param1", "value1" ], [ "param2", "value2" ], [ "param3", "value3" ] ]