使用Ruby Curb进行基本身份验证

时间:2013-05-08 16:14:21

标签: ruby curb

我正在尝试将以下curl命令行自动化为Ruby Curb:

curl -H "Content-Type:application/json" -X POST -d \
 '{"approvalType": "auto", 
  "displayName": "Free API Product",
  "name": "weather_free",
  "proxies": [ "weatherapi" ],
  "environments": [ "test" ]}' \
-u myname:mypass https://api.jupiter.apigee.net/v1/o/{org_name}/apiproducts

在运行脚本之前填写myname,mypass和{org name}。

我不知道如何使用Ruby Curb使用基本身份验证来执行带有JSON有效负载的http帖子。我尝试了以下方法:

require 'json'
require 'curb'

payload = '{"approvalType": "auto", 
  "displayName": "Test API Product Through Ruby1",
  "name": "test_ruby1",
  "proxies": [ "weather" ],
  "environments": [ "test" ]}'

uri = 'https://api.jupiter.apigee.net/v1/o/apigee-qe/apiproducts'
c = Curl::Easy.new(uri)
c.http_auth_types = :basic
c.username = 'myusername'
c.password = 'mypassword'
c.http_post(uri, payload) do |curl| 
    curl.headers["Content-Type"] = ["application/json"]
end

puts c.body_str
puts c.response_code

结果是一个空体和415响应代码。我验证了curl命令完全正常。

任何帮助都会受到高度赞赏,因为它可以解决我现在正在处理的一大类问题。

2 个答案:

答案 0 :(得分:3)

我使用了Curb(0.8.5)并发现,如果我在多个请求中重复使用curl实例(获取保存cookie然后发布数据的请求)并且使用了http_post方法

http_post(uri, payload) 

它实际上会将uri和有效负载组合成单个json请求(这当然会导致错误,例如“意外字符('h'......”或“错误请求”)。

我设法让它工作,但我必须使用带有效负载的方法作为单个参数:

c =Curl::Easy.new
url = "http://someurl.com"
headers={}
headers['Content-Type']='application/json'
headers['X-Requested-With']='XMLHttpRequest'
headers['Accept']='application/json'
payload = "{\"key\":\"value\"}"

c.url = url
c.headers=headers
c.verbose=true
c.http_post(payload)

希望这有帮助。

答案 1 :(得分:0)

415响应代码表示“服务器不支持媒体类型”。如果您将Content-Type设置为这样(没有括号),它是否有效?

curl.headers["Content-Type"] = "application/json"