Search code examples
rubyhttparty

Do not URI encode when using httparty


I have a request setup using httparty and would like to not have URI encoding take place. I have read that there is a class method available

query_string_normalizer proc { |query|
  query.map do |key, value|
    value.map {|v| "#{key}=#{v}"}
  end.join('&')
}

But I am unsure of how to use this in my current setup

url = 'https://url/here/report.json?'
query = { 'param1' => '125894',
          'param2' => 'yesterday',
          'param3' => 'about',
          'param4' => 'client',
          'parameters' => 'ns_ti:*',
          'user' => ENV['USERNAME'],
          'password' => ENV['PASSWORD']
}
response = HTTParty.get(url, query: query)
results = JSON.parse(response.body)

The issue here is that parameters gets encoded and gets sent as 'ns_ti%3A%2A' and I would like to avoid that.


Solution

  • Make your own wrapper for HTTParty and pass a proc to the normalizer that overrides the URI encoding.

    app/config/intializers/rich_lewis_http.rb
    

    .

    class RichLewisHttp
    
      include HTTParty
    
      query_string_normalizer proc { |query|
        query.map do |key, value|
          [value].flatten.map {|v| "#{key}=#{v}"}.join('&')
        end.join('&')
      }
    
    end
    

    Then you can do...

    response = RichLewisHttp.get(url, query: query)
    results = JSON.parse(response.body)