例如,在RestClient控制台中:
RestClient.post 'http://localhost:5001', {:a => 'b'}, :content_type => 'application/json'
Run Code Online (Sandbox Code Playgroud)
这不会将application/json作为内容类型发送.相反,我看到:
Content-Type: application/x-www-form-urlencoded
Run Code Online (Sandbox Code Playgroud)
我能够跟踪对restclient/payload.rb的更改:
class UrlEncoded < Base
...
def headers
super.merge({'Content-Type' => 'application/x-www-form-urlencoded'})
end
end
Run Code Online (Sandbox Code Playgroud)
用super替换super.merge导致内容类型得到尊重,但显然这不是一个真正的解决方案.有谁知道解决这个问题的正确方法?谢谢.
DrC*_*mal 22
您可能希望将json作为字符串作为有效负载而不是散列.例如,执行:
RestClient.post 'http://localhost:5001','{"a":"b"}',:content_type => 'application/json'
Run Code Online (Sandbox Code Playgroud)
如果你查看payload.rb,它表明如果有效负载是字符串,它将使用Base clase而不是UrlEncoded类.试试看,看看那对你有用吗.
Jin*_* Li 10
事实:
对于:post请求,何时payload为a Hash,Content-Type标题将始终被覆盖为application/x-www-form-urlencoded.
可以与rest-client(2.0.0)一起重现.
方案:
将哈希有效负载转换为json字符串.
require 'json'
payload.to_json
Run Code Online (Sandbox Code Playgroud)
在rest-client的回购中有一张票:
我想补充说我的问题是在使用时RestClient::Request.execute(而不是RestClient.post或RestClient.get).
问题在于我的设置:content_type和方式:accept.从我看到的例子中我觉得它们应该像这样的顶级选项:
res = RestClient::Request.execute(
:method => :get,
:url => url,
:verify_ssl => false,
:content_type => :json,
:accept => :json,
:headers => {
:Authorization => "Bearer #{token}",
},
:payload => '{"a":"b"}'
)
Run Code Online (Sandbox Code Playgroud)
但你实际上必须把它们放在:headers这样的:
res = RestClient::Request.execute(
:method => :get,
:url => url,
:verify_ssl => false,
:headers => {
:Authorization => "Bearer #{token}",
:content_type => :json,
:accept => :json
},
:payload => '{"a":"b"}'
)
Run Code Online (Sandbox Code Playgroud)