RAILS 使用 API 密钥 RESTApi 向 onesignal 发送获取请求

RAILS Send get request to onesignal using API Key RESTApi

它是一个 RESTAPI,我需要向 onesignal 发送获取请求。

url = https://onesignal.com/api/v1/apps

他们只提到了这个:

curl --include \
     --header "Authorization: Basic your_key_here" \
 https://onesignal.com/api/v1/apps

我试过这样的方法:

def index
    url = URI.parse('https://onesignal.com/api/v1/apps?apikey=mykey')
    req = Net::HTTP::Get.new(url.to_s)
    res = Net::HTTP.start(url.host, url.port) {|http|
      http.request(req)
    }
    puts res.body
  end

但这不起作用。 结果应该在 json.

我收到这个错误:

<html>
<head><title>400 The plain HTTP request was sent to HTTPS port</title></head>
<body bgcolor="white">
<center><h1>400 Bad Request</h1></center>
<center>The plain HTTP request was sent to HTTPS port</center>
<hr><center>nginx/1.4.6 (Ubuntu)</center>
</body>
</html>

根据 OneSignal webpage 的代码,您的请求应该是:

uri = URI.parse("https://onesignal.com/api/v1/apps")
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true

request = Net::HTTP::Get.new(
  uri.path,
  "Content-Type" => "application/json",
  "Authorization" => "Basic NGXXX...XXXBlNjJj"
)

response = http.request(request) 
puts response.body

在您的案例中,错误与未使用 http.use_ssl = true 有关,但您还需要添加一些其他内容,例如授权 header。