2014-07-23 30 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,它確實有效。

相關問題