rails ruby 中的 RestClient post 请求

RestClient post request in ruby on rails

RestClientpost请求

我尝试了post两种请求方式

@user =  {name: 'xxxxxx', email: 'xxxxxx@gmail.com', password: 'qwertyqqq'}
RestClient.post 'http://localhost:4123/api/users?token=<token>', @user

RestClient::Request.execute(method: :post, url: 'http://localhost:4123/api/v1/users', token: '<token>', payload: '@user', headers: {"Content-Type" => "application/json"})

错误:RestClient::BadRequest:400 错误请求或 RestClient::UnprocessableEntity:422 无法处理的实体

成功案例

当我用 rest 客户端发出 get 请求时,用 curl 就可以了。

RestClient.get 'http://localhost:4123/api/v1/users?token=<token>'

卷曲:

获取请求:

curl -X GET http://localhost:4123/api/v1/users/1?token=<token>

Post 请求帮助:

curl -d '{"name":"xxxx","email":"xxxx@gmail.com","password":"12345678", "admin": true, "role":"admin"}' -H "Content-Type: application/json" -X POST http://localhost:4123/api/v1/users?token=<token>

CURL 版本和 RestClient 版本的区别在于,在 CURL 版本中,您发送一个 JSON 字符串作为有效负载,但在 [=12= =] 发送字符串 '@user'

实际发送时应该没问题JSON:

RestClient.post(
  "http://localhost:4123/api/v1/users?token=<token>", 
  @user.to_json, 
  { content_type: :json, accept: :json }
)