2014-07-23 906 views
0

我正在发出GET请求来搜索某些列表。我正在测试的关键字是iphone 5为什么'+'被转换为'%2B',我该如何防止?

做当:

m = Marktplaats.new 
m.search(keyword: 'iphone 5') 

我得到不相关的数据。

下面是我使用的代码:

require 'httparty' 

class Marktplaats 
    include HTTParty 

    base_uri('https://api.marktplaats.nl') 

    def search(keyword) 

    # Debug 
    puts search_query_params(keyword) 
    puts last_uri(self.class.get('/api3/ads.json', query: search_query_params(keyword))) 

    self.class.get('/api3/ads.json', query: search_query_params(keyword)) 
    end 

    def view(urn) 
    self.class.get("/api3/ads/#{urn}.json", query: default_query_params) 
    end 

    def categories 
    self.class.get('/api3/categories.json', query: default_query_params) 
    end 

    protected 

    def default_query_params 
     { 
     oauth_token: '1me6jq76h8t6rim747m7bketkd', 
     api_ver: '3.7', 
     session: 'ebc565b8-659f-40f6-9d0a-96986f1d1595', 
     screenWidth: '62', 
     screenHeight: '111', 
     app_ver: 'Android3.1.0' 
     } 
    end 

    def search_query_params(args = {}) 
     search_params = { 
     q: split_keyword(args[:keyword]), 
     searchOnTitleAndDescription: args[:search_on_title_and_description] || 'false', 
     showListings: args[:show_listings] || 'true', 
     categoryId: args[:category_id] || '1953', 
     page: args[:page] || '1', 
     size: args[:size] || '30', 
     sortBy: args[:sort_by] || 'DEFAULT', 
     sortOrder: args[:sort_order] || 'DESCENDING', 
     showHistograms: args[:show_histograms] || 'true' 
     } 
     merge_params(default_query_params, search_params) 
    end 

    def merge_params(params1, params2) 
     params1.merge(params2) 
    end 

    def split_keyword(keyword) 
     keyword.gsub(' ', '+') 
    end 

    def last_uri(last_request) 
     last_request.request.last_uri 
    end 
end 

puts search_query_params(keyword)回报:

{:oauth_token=>"1me6jq76h8t6rim747m7bketkd", :api_ver=>"3.7", :session=>"ebc565b8-659f-40f6-9d0a-96986f1d1595", :screenWidth=>"62", :screenHeight=>"111", :app_ver=>"Android3.1.0", :q=>"iphone+5", :searchOnTitleAndDescription=>"true", :showListings=>"false", :categoryId=>"1953", :page=>"1", :size=>"30", :sortBy=>"DEFAULT", :sortOrder=>"DESCENDING", :showHistograms=>"true"} 

last_uri(self.class.get('/api3/ads.json', query: search_query_params(keyword)))回报:

https://api.marktplaats.nl/api3/ads.json?oauth_token=1me6jq76h8t6rim747m7bketkd&api_ver=3.7&session=ebc565b8-659f-40f6-9d0a-96986f1d1595&screenWidth=62&screenHeight=111&app_ver=Android3.1.0&q=iphone%2B5&searchOnTitleAndDescription=false&showListings=true&categoryId=1953&page=1&size=30&sortBy=DEFAULT&sortOrder=DESCENDING&showHistograms=true 

我认为这是与请求URI。关键字之间的+符号显示为%2B。所以iphone+5显示为iphone%2B5。如果我在URI中将iphone%2B5替换为iphone+5,它将返回正确的数据。

问题是如何防止在使用HTTParty进行GET请求时,+符号转换为%2B

注意: 这可能是什么the Tin Man谈论时,他评论here

回答

0

我通过从类中删除#split_keyword(keyword)方法解决了这个问题,因此不再使用它。

看来我并不需要手动将' '替换为+之间的字符。如果我这样做,他们会转换为%2B这似乎不工作。

没有人工更换,' '得到转换为%20,它确实有效。