2

我正在尝试将以下 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 命令可以正常工作。

任何帮助将不胜感激,因为它将解决我现在正在处理的一整类问题。

4

2 回答 2

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)

希望这可以帮助。

于 2013-11-19T08:04:35.587 回答
0

415 响应代码表示“服务器不支持媒体类型”。如果您像这样设置 Content-Type(不带括号),它会起作用吗?

curl.headers["Content-Type"] = "application/json"
于 2013-05-08T16:21:02.073 回答