在Rails 4.2中,我使用HTTParty
爲SendGrid的API版本3製作了一個API包裝器。這是什麼樣子: curl做的時候HTTParty補丁請求不起作用
class SendGridV3
include HTTParty
debug_output $stdout
base_uri 'https://api.sendgrid.com/v3'
format :json
headers 'Authorization' => "Bearer #{ENV['SENDGRID_API_KEY']}"
def self.enforce_tls
response = patch '/user/settings/enforced_tls', query: {require_tls: true}.to_json
puts response
response['require_tls']
end
end
當我運行SendGridV3.enforce_tls
預期的反應是{"require_tls": true, "require_valid_cert": false}
但實際響應{"require_tls": false, "require_valid_cert": false}
這裏是debug_output
opening connection to api.sendgrid.com:443...
opened
starting SSL for api.sendgrid.com:443...
SSL established
<- "PATCH /v3/user/settings/enforced_tls?{%22require_tls%22:true} HTTP/1.1\r\nAuthorization: Bearer MY-SENDGRID-KEY\r\nConnection: close\r\nHost: api.sendgrid.com\r\nContent-Length: 0\r\nContent-Type: application/x-www-form-urlencoded\r\n\r\n"
<- ""
-> "HTTP/1.1 200 OK\r\n"
-> "Server: nginx\r\n"
-> "Date: Fri, 25 Aug 2017 18:47:15 GMT\r\n"
-> "Content-Type: application/json\r\n"
-> "Content-Length: 48\r\n"
-> "Connection: close\r\n"
-> "Access-Control-Allow-Methods: HEAD, PATCH, OPTIONS, GET\r\n"
-> "Access-Control-Max-Age: 21600\r\n"
-> "Access-Control-Expose-Headers: Link\r\n"
-> "Access-Control-Allow-Origin: *\r\n"
-> "Access-Control-Allow-Headers: AUTHORIZATION, Content-Type, On-behalf-of, x-sg-elas-acl\r\n"
-> "Content-Security-Policy: default-src https://api.sendgrid.com; frame-src 'none'; object-src 'none'\r\n"
-> "X-Content-Type-Options: nosniff\r\n"
-> "Strict-Transport-Security: max-age=31536000\r\n"
-> "X-Ratelimit-Remaining: 599\r\n"
-> "X-Ratelimit-Limit: 600\r\n"
-> "X-Ratelimit-Reset: 1503686880\r\n"
-> "Powered-By: Mako\r\n"
-> "\r\n"
reading 48 bytes...
-> "{\"require_tls\":false,\"require_valid_cert\":false}"
read 48 bytes
Conn close
{"require_tls"=>false, "require_valid_cert"=>false}
=> false
輸出我也嘗試過使用body:
代替query:
傳入JSON中
我得到預期的迴應時,我用這個捲曲:
curl -X "PATCH" "https://api.sendgrid.com/v3/user/settings/enforced_tls" -H "Authorization: Bearer MY-SENDGRID-KEY" -H "Content-Type: application/json" -d '{"require_tls":true}'
因此,如何捲曲使這項工作,同時HTTParty失敗的原因?
難道是內容類型嗎?在你的調試中,它說:「PATCH/v3/user/settings/enforced_tls?{%22require_tls%22:true} HTTP/1.1 \ r \ n授權:承載者MY-SENDGRID-KEY \ r \ n連接:關閉\ r \ n主機:api.sendgrid.com \ r \ n內容長度:0 \ r \ n內容類型:application/x-www-form-urlencoded \ r \ n \ r \ n「'這可能是您需要明確將它設置爲'application/json',因此它現在看起來像是'x-www-form-urlencoded'。 –
斑點@JamesMilani你是對的。我設置了內容類型並將'query:'更改爲'body:'並且它可以工作。 –
嘿託比。我將把它變成一個答案。我在我自己的應用程序中以這種方式實現'HTTParty'。乾杯! –