我应该如何使用带有"application/x-www-form-urlencoded"和"multipart/form-data;"标头的post方法在法拉第中发送此JSON?
message = {
"name":"John",
"age":30,
"cars": {
"car1":"Ford",
"car2":"BMW",
"car3":"Fiat"
}
}
我试过:
conn = Faraday.new(url: "http://localhost:8081") do |f|
f.request :multipart
f.request :url_encoded
f.adapter :net_http
end
conn.post("/", message)
此 cURL 请求有效
curl -X POST
http://localhost:8081
-H 'Content-Type: application/x-www-form-urlencoded'
-H 'content-type: multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW'
-F 'message=2018-12-27 12:52'
-F source=RDW
-F object_type=Responses
但我不太知道如何让它在法拉第工作。此外,cURL 请求中的数据不是嵌套的 JSON,因此我需要能够动态创建请求的正文,因为我不会提前知道 JSON 的确切结构。
如果您需要更多详细信息或清晰度,请提出任何问题。
谢谢!
POST 的默认内容类型是x-www-form-urlencoded
,因此将自动对哈希进行编码。JSON没有这样的自动数据处理,这就是为什么下面的第二个示例传入哈希的字符串化表示形式。
Faraday.new(url: 'http://localhost:8081').post('/endpoint', {foo: 1, bar: 2})
# => POST http://localhost:8081/endpoint
# with body 'bar=2&foo=1'
# including header 'Content-Type'=>'application/x-www-form-urlencoded'
Faraday.new(url: 'http://localhost:8081').post('/endpoint', {foo: 1, bar: 2}.to_json, {'Content-Type'=>'application/json'})
# => POST http://localhost:8081/endpoint
# with body '{"foo":1,"bar":2}'
# including header 'Content-Type'=>'application/json'
我不确定你打算做什么,但你可以发送如下内容
Faraday.new(url: 'http://localhost:8081').post('/endpoint', {foo: 1, bar: 2}.to_json)
# => POST http://localhost:8081/endpoint
# with body '{"foo":1,"bar":2}'
# including header 'Content-Type'=>'application/x-www-form-urlencoded'
但是,这将被解释为在 Ruby 中{"{"foo":1,"bar":2}" => nil}
。如果你在另一端解析数据,你可以让它工作,但总是更难打破惯例。
对于 POST 请求,Faraday 希望表单数据作为 JSON 字符串,而不是 Ruby 哈希。这可以通过使用 json gem 的Hash#to_json
方法轻松实现,如下所示:
require 'json'
url = 'http://localhost:8081'
form_data = {
name: 'John',
age: '30',
cars: {
car1: 'Ford',
car2: 'BMW',
car3: 'Fiat'
}
}.to_json
headers = {}
Faraday.post(url, form_data, headers)
或者在您的实例中只是简单地:
conn = Faraday.new(url: "http://localhost:8081") do |f|
f.request :multipart
f.request :url_encoded
f.adapter :net_http
end
# exact same code, except just need to call require json and call to_json here
require 'json'
conn.post("/", message.to_json)