webc.rb

Ruby code posted by kaecy
created at 26 Jan 13:17, updated at 26 Jan 13:52

Edit | Back
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
require "socket";
require "uri";

# urlencoded type: application/x-www-form-urlencoded

class WebClient
  attr_writer :action, :type;
  attr_reader :initial_line, :headers, :content;

  def initialize server, port = 80
    @server, @port = server, port;
    @action = "GET";
    @type = "text/plain";
  end

  def request location, data=nil
    socket = TCPSocket.new @server, @port;

    if data != nil and @action == 'GET'
      @action = 'POST';
    end

    socket.write "#{@action} #{URI.escape(location)} HTTP/1.0\r\n";
    socket.write "Host: #{@server}\r\n";

    if data != nil
      socket.write "Content-Type: #{@type}\r\n";
      socket.write "Content-Length: #{data.length}\r\n";
    end

    socket.write "\r\n";
    socket.write data;

    @initial_line = socket.readline;

    @headers = {};
    while (line = socket.readline) != "\r\n"
      @headers.store *line.downcase.strip.split(/:\s+/);
    end

    @content = socket.read;
  end
end
970 Bytes in 3 ms with coderay