Search code examples
ruby-on-railsrubypostnet-http

Missing query parameters on x-www-form-urlencoded POST request and net/http


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.


Solution

  • 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)