【问题标题】:net::http help [ POST works with curl but fails on the form]net::http 帮助 [ POST 与 curl 一起使用,但在表单上失败]
【发布时间】:2013-03-26 23:56:30
【问题描述】:

我正在尝试使用 net::http 进行发布请求。

我使用 net:http 的请求失败并出现以下错误:

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 代码适用于执行完全相同的不同发布请求(在不同 uri 上)。

服务期望以 json 格式发送和接收数据。

关于调试的任何建议。

谢谢!

更新: 添加了我设置标题的方式

【问题讨论】:

  • 你如何在 net::http 代码中为 curl -H 'Content-Type: application/json' 设置等效标题?我看不到它。 . .我希望看到request.header 或类似的(要检查正确的语法......)

标签: ruby json post curl net-http


【解决方案1】:

试试:

request = Net::HTTP::Post.new(uri.request_uri, {'Content-Type' =>'application/json'})

或:

request = Net::HTTP::Post.new(uri.request_uri)
request["Content-Type"] = "application/json"

【讨论】:

  • 谢谢尼尔。我添加了设置标题的方式。基本上我做 request.add_field(key,value) 并且它适用于我正在发出的其他帖子请求。我的预感是在我传递的数据中,但我不确定(验证失败可能意味着 json 数据验证?)
  • 还尝试了 request[key]=value 而不是使用 request.add_field 。它仍然失败并出现相同的错误
猜你喜欢
  • 2017-10-14
  • 1970-01-01
  • 2019-01-04
  • 1970-01-01
  • 2017-05-29
  • 1970-01-01
  • 2011-11-14
  • 1970-01-01
  • 2018-11-05
相关资源
最近更新 更多