【问题标题】:Doing a Post with Ruby Curb with basic authentication使用带有基本身份验证的 Ruby Curb 发布帖子
【发布时间】:2013-11-19 16:04:35
【问题描述】:

我正在尝试将以下 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 命令运行良好。

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

【问题讨论】:

  • 在 curl 中有 -vv 命令来显示详细的输出,你可以尝试同样的方式来遏制?

标签: ruby curb


【解决方案1】:

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

http_post(uri, payload) 

它实际上会发送 uri 和 payload 组合成单个 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)

希望这会有所帮助。

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

    • 不幸的是,这并没有解决问题。我仍然得到一个空白的正文和一个 415 响应
    猜你喜欢
    • 2013-03-19
    • 2014-01-30
    • 1970-01-01
    • 2014-09-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-31
    相关资源
    最近更新 更多