使用Ruby的Net:HTTP保留HTTP头中的大小写 [英] Preserving case in HTTP headers with Ruby's Net:HTTP
问题描述
虽然HTTP规范说标题不区分大小写; Paypal及其新的自适应支付API要求其标题区分大小写。
Although the HTTP spec says that headers are case insensitive; Paypal, with their new adaptive payments API require their headers to be case-sensitive.
使用PayPal自适应支付扩展程序为ActiveMerchant( http://github.com/lamp/paypal_adaptive_gateway )虽然标题设置在所有大写字母中,但它们是以大小写形式发送的。
Using the paypal adaptive payments extension for ActiveMerchant (http://github.com/lamp/paypal_adaptive_gateway) it seems that although the headers are set in all caps, they are sent in mixed case.
以下是发送HTTP请求的代码:
Here is the code that sends the HTTP request:
headers = {
"X-PAYPAL-REQUEST-DATA-FORMAT" => "XML",
"X-PAYPAL-RESPONSE-DATA-FORMAT" => "JSON",
"X-PAYPAL-SECURITY-USERID" => @config[:login],
"X-PAYPAL-SECURITY-PASSWORD" => @config[:password],
"X-PAYPAL-SECURITY-SIGNATURE" => @config[:signature],
"X-PAYPAL-APPLICATION-ID" => @config[:appid]
}
build_url action
request = Net::HTTP::Post.new(@url.path)
request.body = @xml
headers.each_pair { |k,v| request[k] = v }
request.content_type = 'text/xml'
proxy = Net::HTTP::Proxy("127.0.0.1", "60723")
server = proxy.new(@url.host, 443)
server.use_ssl = true
server.start { |http| http.request(request) }.body
(我添加了代理行,所以我可以看到是什么继续与查尔斯 - http://www.charlesproxy.com/ )
(i added the proxy line so i could see what was going on with Charles - http://www.charlesproxy.com/)
当我查看查尔斯的请求标题时,这就是我所看到的:
When I look at the request headers in charles, this is what i see:
X-Paypal-Application-Id ...
X-Paypal-Security-Password...
X-Paypal-Security-Signature ...
X-Paypal-Security-Userid ...
X-Paypal-Request-Data-Format XML
X-Paypal-Response-Data-Format JSON
Accept */*
Content-Type text/xml
Content-Length 522
Host svcs.sandbox.paypal.com
我确认它是不是Charles通过使用curl运行类似的请求来进行大小写转换。在该测试中,案例被保留。
I verified that it is not Charles doing the case conversion by running a similar request using curl. In that test the case was preserved.
推荐答案
RFC确实指定标题键是不区分大小写,所以不幸的是,您似乎遇到了PayPal API的烦人需求。
The RFC does specify that header keys are case-insensitive, so unfortunately you seem to have hit an annoying requirement with the PayPal API.
Net :: HTTP正在改变这种情况,虽然我很惊讶它们并非全都下降:
Net::HTTP is what is changing the case, although I'm surprised they're not all getting downcased:
# File net/http.rb, line 1160
def []=(key, val)
unless val
@header.delete key.downcase
return val
end
@header[key.downcase] = [val]
end
设置与不区分大小写的键对应的标题字段。
"Sets the header field corresponding to the case-insensitive key."
由于上面是一个简单的类,它可能是猴子修补。我会进一步思考一个更好的解决方案。
As the above is a simple class it could be monkey-patched. I will think further for a nicer solution.
这篇关于使用Ruby的Net:HTTP保留HTTP头中的大小写的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!