Ruby http帮助[POST与curl一起工作,但在表单上失败]
我正在尝试使用net::http来执行post请求 使用net:http的请求失败,错误如下:Ruby http帮助[POST与curl一起工作,但在表单上失败],ruby,json,post,curl,net-http,Ruby,Json,Post,Curl,Net Http,我正在尝试使用net::http来执行post请求 使用net:http的请求失败,错误如下: respnose_body,code: ["{\"message\":\"Validation Failed\",\"errors\":{\"direction\":[\"invalid\"]}}", "422"]] 我的请求可以在终端上使用curl: curl https://$$.com/$$ \ > -u usr:Pssd! \ > -X POST \ >
respnose_body,code: ["{\"message\":\"Validation Failed\",\"errors\":{\"direction\":[\"invalid\"]}}",
"422"]]
我的请求可以在终端上使用curl:
curl https://$$.com/$$ \
> -u usr:Pssd! \
> -X POST \
> -H 'Accept: application/json' \
> -H 'Content-Type: application/json' \
> -d '{"body":"my body"}'
但是,对于相同的请求,我尝试使用nett:http作为
http_headers => {"Accept" => "application/json", "Content-Type" => "application/json"}
uri=URI.parse(url)
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true
http.verify_mode = OpenSSL::SSL::VERIFY_NONE
request = Net::HTTP::Post.new(uri.request_uri)
http_headers.each{|key,value| request.add_field(key,value)}
request.body = form_data
response=http.request(request)
The form_data is passed as a json using hash.to_json .
现在,相同的NET:HTTP代码适用于执行完全相同的不同post请求(在不同的uri上)
该服务期望数据以json的形式发送和接收
任何关于调试这个的建议
谢谢
更新:
添加了设置标题的方式尝试:
request = Net::HTTP::Post.new(uri.request_uri, {'Content-Type' =>'application/json'})
或:
如何将等效头设置为net::http代码中的curl
-H'Content-Type:application/json'
?我看不到。我希望看到一个请求.header
或类似的(检查语法是否正确…)谢谢Neil。我添加了设置标题的方式。基本上我做请求。添加_字段(key,value),它对我正在做的其他post请求有效。我的直觉是我正在传递的数据中有它,但我不确定(验证失败可能意味着json数据验证?)也尝试了request[key]=value,而不是使用request.add_字段。它仍然失败,并出现相同的错误
request = Net::HTTP::Post.new(uri.request_uri)
request["Content-Type"] = "application/json"