问题描述
这里是使用 curl 的请求:
So here's the request using curl:
curl -XPOST -H content-type:application/json -d "{"credentials":{"username":"username","key":"key"}}" https://auth.api.rackspacecloud.com/v1.1/auth
我一直在尝试使用 ruby 发出同样的请求,但我似乎无法让它工作.
I've been trying to make this same request using ruby, but I can't seem to get it to work.
我也尝试了几个库,但我无法让它工作.这是我到目前为止所拥有的:
I tried a couple of libraries also, but I can't get it to work.Here's what I have so far:
uri = URI.parse("https://auth.api.rackspacecloud.com")
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true
http.verify_mode = OpenSSL::SSL::VERIFY_NONE
request = Net::HTTP::Post.new("/v1.1/auth")
request.set_form_data({'credentials' => {'username' => 'username', 'key' => 'key'}})
response = http.request(request)
我收到 415 不受支持的媒体类型错误.
I get a 415 unsupported media type error.
推荐答案
您已经很接近了,但还远远不够.试试这样的:
You are close, but not quite there. Try something like this instead:
uri = URI.parse("https://auth.api.rackspacecloud.com")
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true
http.verify_mode = OpenSSL::SSL::VERIFY_NONE
request = Net::HTTP::Post.new("/v1.1/auth")
request.add_field('Content-Type', 'application/json')
request.body = {'credentials' => {'username' => 'username', 'key' => 'key'}}.to_json
response = http.request(request)
这将设置 Content-Type 标头并在正文中发布 JSON,而不是像您的代码那样在表单数据中发布.使用示例凭据,它仍然失败,但我怀疑它应该可以使用其中的真实数据.
This will set the Content-Type header as well as post the JSON in the body, rather than in the form data as your code had it. With the sample credentials, it still fails, but I suspect it should work with real data in there.
这篇关于如何在 ruby 中通过 SSL 调用 HTTP POST 方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!