如何在ruby中通过SSL调用HTTP POST方法? [英] How to invoke HTTP POST method over SSL in ruby?

查看:256
本文介绍了如何在ruby中通过SSL调用HTTP POST方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这里是使用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)


$ b b

我收到415不支持的媒体类型错误。

I get a 415 unsupported media type error.

推荐答案

尝试这样的代替:

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'}}
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方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆