当curl执行时,HTTParty补丁请求不起作用

时间:2017-08-25 19:12:06

标签: ruby-on-rails rest httparty

在Rails 4.2中,我使用HTTParty为SendGrid的API版本3制作API包装器。这就是它的样子:

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失败时curl如何使这个工作?

2 个答案:

答案 0 :(得分:1)

明确设置Content-Type以及使用:body将使其有效。

class SendGridV3
  ...
  headers 'Content-Type' => 'application/json'
  def self.enforce_tls
    response = patch '/user/settings/enforced_tls', body: {require_tls: true}.to_json
    puts response
    response['require_tls']
  end
end

向OP提供归因,指出在此用例中:query需要:body

答案 1 :(得分:0)

我认为查询中的.to_json导致了问题,HTTParty将ruby hash与其解析的query参数一起创建查询字符串。 .to_json导致query参数成为字符串,因此查询将按原样传递以构造URI。从那里删除.to_json应该可以解决问题。