简体   繁体   English

使用rest_client从rails发送发布请求。400错误的请求

[英]Sending post request from rails with rest_client.. 400 Bad request

Basically, I want to send post request to a faye server. 基本上,我想将发布请求发送到faye服务器。 When I use curl, It works, 当我使用curl时,它会起作用,

curl http://localhost:9292/faye -d 'message={"channel":"/messages/new", "data":"hello"}'

I can see hello in client. 我可以在客户端中打个招呼。

but when I use http_party or the rest_client or net http, It says bad request. 但是当我使用http_party或rest_client或net http时,它表示请求错误。

def send

     params = {'channel' => 'faye/messages/new','data' => 'hello', "Content-type" => "application/json"}
     x = Net::HTTP::Post.new (URI.parse('http://localhost:9292/faye'))
     puts x.body

    # I tried it with http_ party too and rest_cliet.
    #  data = {
    #    channel: "messages/new",
    #    data: "hello"
    #  }
    #  RestClient.post 'http://localhost:9292/faye', :channel => 'messages/new', :data=> "hello"
    # response = RestClient::Request.execute(method: :post, url: '127.0.0.1:9292/faye',messages: {"channel" => "messages/new", "data"=>"hello"})
   end
end

I have tried slolutions from Submitting POST data from the controller in rails to another website 我已经尝试过将控制器中的POST数据提交到其他网站中而产生的浪费

and Ruby on Rails HTTPS Post Bad Request but it still says bad request. Ruby on Rails HTTPS发布错误请求,但仍然显示错误请求。

I dont know where I am making mistake. 我不知道我在哪里犯错。 I have been pulling my hair in this for some days. 这几天我一直在梳头。 My ruby version is 2.2.4 rails -v => 4.2.5 我的红宝石版本是2.2.4 rails -v => 4.2.5

Edit: with help from accepted answer, I update my method. 编辑:在接受的答案的帮助下,我更新了我的方法。 Its working now. 现在正在工作。

require 'rest_client'
   require 'json'
   def send
     RestClient.post 'http://localhost:9292/faye', {message: {"channel" => "/messages/new", "data"=>"hello"}.to_json}, {:content_type => :json, :accept => :json}
   end

In your curl example you're sending json data, but not when using Ruby. 在您的curl示例中,您正在发送json数据,但在使用Ruby时不发送。 Try this 尝试这个

require "json"
RestClient.post("http://localhost:9292/faye", {
  message: {"channel" => "messages/new", "data"=>"hello"}.to_json
})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM