I am using the HTTParty gem in a Ruby on Rails app to make requests to my Google Cloud Storage bucket. Google returns a status code of 400 saying 'Bad Request' but does not give a reason for the error. I have verified that the authorization is not the problem. Here is my code:
module Google
class Client
include HTTParty
base_uri "https://www.googleapis.com"
def get_pics
self.class.get("/storage/v1/b/bucket-name/o?key=<%= ENV['GOOGLE_KEY'] %>")
end
end
end
Then in the controller:
class WelcomeController < ApplicationController
def index
response = Google::Client.new.get_pics
end
end
Here is the response I am getting:
#<HTTParty::Response:0x7f8826f71268 parsed_response="<HTML>\n<HEAD>\n<TITLE>Bad Request</TITLE>\n</HEAD>\n<BODY
BGCOLOR=\"#FFFFFF\" TEXT=\"#000000\">\n<H1>Bad Request</H1>\n<H2>Error 400</H2>\n</BODY>\n</HTML>\n", @response=#<Net::HTTPBadRequest
400 Bad Request readbody=true>, @headers={"content-type"=>["text/html;
charset=UTF-8"], "content-length"=>["145"], "date"=>["Thu, 12 Nov 2015
04:02:14 GMT"], "expires"=>["Thu, 12 Nov 2015 04:02:14 GMT"],
"cache-control"=>["private, max-age=0"], "x-content-type-options"=>
["nosniff"], "x-frame-options"=>["SAMEORIGIN"], "x-xss-protection"=>["1; mode=block"],
"server"=>["GSE"], "alternate-protocol"=>["443:quic,p=1"],
"alt-svc"=>["quic=\":443\"; p=\"1\"; ma=604800"], "connection"=>["close"]}>
This could be a lot of things, but the most likely reason is that your key is invalid. The most common reason that your key is invalid is that you are accidentally using the "key ID" of a service account and not an actual "API key" (they're easy to confuse).
To generate an API key, head to http://console.developers.google.com , open the toolbar, choose "API Manager", then choose the "Credentials" page. Ignore everything under the "Service account keys" section, even if it says "Key ID". Those are service account keys.
Instead, click "new credentials" and choose "API key". Choose "Server Key" or "Browser Key" in the popup (server key if you're gonna use it from your rails server, browser if it runs client side). Now, try using that new key.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.