我有一个Google Places API密钥,并且能够从我的localhost成功查询Google Places API。
我在Rails 3.1上,当我将我的网站推送到Heroku时,我得到了一个糟糕的请求。我指的是http google places API而不是javascript版本 - 虽然我怀疑这个问题会是相同的(请参阅下面我从Google获得的消息)
以下是我在Google控制台中配置帐户的方式:
Key for browser apps (with referers)
API key:
XXXXXX
Referers:
Any referer allowed
Activated on: Mar 5, 2013 9:41 PM
Activated by: xx@stanford.edu –
当我在当地主持人时没有问题。
然而,当我推送应用程序然后查询Google地方信息时,我就是这样:
bad URI(is not URI?): https://maps.googleapis.com/maps/api/place/textsearch/json?query=blamp&key=XXXXX&sensor=false&types=restaurant|food|bar|cafe
编辑: 我确定错误是因为我使用了条形'|'在最后分开谷歌类型。但是,当我将查询复制/粘贴到浏览器标题时,以及当我在localhost上进行开发时,这都有效。任何想法:
1)为什么会这样。 2)如何解决?
以下是我使用Ruby代码访问API的方法:
query = URI.escape(params[:search])
url_params = "json?query="+ query + "&key="+ GOOGLE_API_KEY + "&sensor="+ false.to_s + "&types="+GOOGLE_TYPES.join("|")
url_params << "&pagetoken="+params[:next_token] if params[:next_token]
url = URI.parse("https://maps.googleapis.com/maps/api/place/textsearch/"+url_params)
http = Net::HTTP.new(url.host, url.port)
http.use_ssl = true
http.verify_mode = OpenSSL::SSL::VERIFY_NONE
request = Net::HTTP::Get.new(url.request_uri)
result = http.request(request)
JSON.parse(result.body)
关于GOOGLE_TYPES的说明:这是一个全局常量,实际上是一个数组;我加入“|”然后将其传递给URL。
问题在于,当我对字符串进行URI.encode时,查询不会返回任何简单请求的结果,例如“牛排屋旧金山”,而在URI.encode之前它会返回。如果查询无法像在localhost上那样返回正确的结果,则查询变得无用。
答案 0 :(得分:2)
也许您应该对您的网址进行编码。始终使用请求和参数对URL进行编码是一种很好的做法。这可能有所帮助:URI::InvalidURIError (bad URI(is not URI?): ):
编辑: 网址字符“|”可能不安全,因此需要对这些查询进行url编码。
试试这个:
def search_google_places
api_key = 'xxx'
base_url = 'https://maps.googleapis.com/maps/api/place/textsearch/json?key=' + api_key
tail_url = '&query=garena&sensor=false&types=restaurant|food|bar|cafe'
main_url = base_url + api_key + tail_url
url = URI.parse(URI.encode(main_url))
response = Net::HTTP.start(url.host, use_ssl: true, verify_mode:
OpenSSL::SSL::VERIFY_NONE) do |http|
http.get url.request_uri
end
case response
when Net::HTTPRedirection
# repeat the request using response['Location']
when Net::HTTPSuccess
outputData = JSON.parse response.body
else
# response code isn't a 200; raise an exception
pp response.error!
end
return outputData
end