2013-05-08 34 views
2

我想下面的curl命令行到紅寶石路沿石自動化:做一個帖子用Ruby遏制基本身份驗證

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和{組織名稱}是運行腳本填充之前。

我不知道如何使用Ruby Curb使用基本身份驗證來執行帶有JSON負載的http post。我嘗試了以下方法:

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命令完美無缺。

任何幫助將不勝感激,因爲它可以解決我現在正在處理的一整類問題。

+0

curl有-vv命令來顯示詳細的輸出,你可以嘗試相同的路邊? – poseid 2013-05-08 16:20:19

回答

0

415響應碼指示「服務器不支持媒體類型」。如果你像這樣設置Content-Type(沒有括號),它工作嗎?

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

不幸的是,這並沒有解決問題。我仍然得到一個空白的身體和415響應 – 2013-05-08 21:39:50

3

我用路邊(0.8.5),並發現了,如果我再利用捲曲例如在多個請求(GET請求來保存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) 

希望這會有所幫助。