루비, 각 파라미터를 암시 적으로 진술하지 않고 API 요청을 형성하기
-
14-11-2019 - |
문제
웹 서비스를 요청하려고합니다 ( fwix ) 및 내 레일에서앱을 작성한 다음 이니셜 라이저를 만들었습니다. 이는 작동합니다 ... Sorta, 나는 두 가지 문제가 있지만,
-
어떤 이유로 매개 변수의 값은 공백으로 PeranaCodicetagode의 값을 가져야 할 필요가 있습니다. 루비로 성취 할 수있는 표준은 무엇입니까?또한 URL을 형성하는 표준 방법은 무엇입니까?나는 그 공간이
+
라고 생각했다. -
내 코드에서 보낸 옵션을 어떻게 수행 할 수 있으며
%20
와 같은 각각을 명시하는 대신에 사용하는 대신 사용할 수 있습니다.다음은 내 코드입니다. 문제가있는 문제 공간 마지막 방법의 각 매개 변수에 대해
query_items << "api_key=#{options[:api_key]}" if options[:api_key]
로 시작하는 라인은 멋질 것입니다!
.require 'httparty' module Fwix class API include HTTParty class JSONParser < HTTParty::Parser def json JSON.parse(body) end end parser JSONParser base_uri "http://geoapi.fwix.com" def self.query(options = {}) begin query_url = query_url(options) puts "querying: #{base_uri}#{query_url}" response = get( query_url ) rescue raise "Connection to Fwix API failed" if response.nil? end end def self.query_url(input_options = {}) @defaults ||= { :api_key => "my_api_key", } options = @defaults.merge(input_options) query_url = "/content.json?" query_items = [] query_items << "api_key=#{options[:api_key]}" if options[:api_key] query_items << "province=#{options[:province]}" if options[:province] query_items << "city=#{options[:city]}" if options[:city] query_items << "address=#{options[:address]}" if options[:address] query_url += query_items.join('&') query_url end end end
해결책
def self.query_url(input_options = {})
options = {
:api_key => "my_api_key",
}.merge(input_options)
query_url = "/content.json?"
query_items = []
options.each { |k, v| query_items << "#{k}=#{v.gsub(/\s/, '+')}" }
query_url += query_items.join('&')
end
다른 팁
For 1) You API provider is expecting '+' because the API is expecting in a CGI formatted string instead of URL formatted string.
require 'cgi'
my_query = "hel lo"
CGI.escape(my_query)
this should give you
"hel+lo"
as you expect
for Question 2) I would do something like
query_items = options.keys.collect { |key| "#{key.to_s}=#{options[key]}" }
I'm a developer at Fwix and wanted to help you with your url escaping issue. However, escaping with %20 works for me:
wget 'http://geoapi.fwix.com/content.xml?api_key=mark&province=ca&city=san%20francisco&query=gavin%20newsom'
I was hoping you could provide me with the specific request you're making that you're unable to escape with %20.