开发者

Ruby - Problem with HTTP Post

this is my code:

   @data = "somedata\r\nsomadata\r\nsomadata\r\n"
   uri = URI.parse(my_url)
   http = Net::HTTP.new(uri.host, uri.port)
   resp, body = http.post(uri.path, @data)

When I try to run this, I get a 'sysread' error, saying that the end of file was reached (EOFError). Note that if I remove the \r of @data, the error doesn't occur, but I really need it.

I'm using Ruby 1.8.7, but a similar problem accurred with 1.9.2.

I am trying to convert a PHP class to Ruby, Here i开发者_JAVA百科s the PHP code:

$req = 'somedata\r\nsomadata\r\nsomadata\r\n';
$r = new HttpRequest($url, HttpRequest::METH_POST);
$r->addRawPostData($req);
$resp = $r->send()->getBody();

Thanks!


You can't use newlines in Http Post! If you are developing a web application you can use the standard br tag. What are you trying to make?


This is a shot in the dark but the default ContentType for net/http post is "x-www-form-urlencoded". Try setting the ContentType in the header to "text/plain". Take a look at the net/http docs for how to set the header.


Slightly late answer but I hope it helps.

Your code works with ruby 2.5.0p0 so possibly the error was caused by ruby standard library and got fixed meanwhile.

I tried with local sinatra server (ruby simple-server.rb):

require 'sinatra'

post '/*' do
  puts "I got #{params}"
end

And your code (ruby example.rb):

require 'uri'
require 'net/http'
my_url = "http://localhost:4567/"
@data = "somedata\r\nsomadata\r\nsomadata\r\n"
uri = URI.parse(my_url)
http = Net::HTTP.new(uri.host, uri.port)
resp, body = http.post(uri.path, @data)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜