這是非常有用的,但請注意的Net :: HTTP#exec方法標記僅供內部使用。可能是因爲它沒有做資源管理等
以下工作相適應的建議的戰略覆蓋的Net :: HTTP#連接(連接到插座)。我喜歡使用HTTParty gem來處理我的HTTP請求。所以這裏的策略使用了一個用於HTTParty的自定義ConnectionAdaptor。現在,我只需更改我的包含類中的:: default_params = call,以控制我們是使用Unix還是TCP/HTTP套接字。
###########################################################
# net/socket_http.rb
###########################################################
module Net
# Overrides the connect method to simply connect to a unix domain socket.
class SocketHttp < HTTP
attr_reader :socket_path
# URI should be a relative URI giving the path on the HTTP server.
# socket_path is the filesystem path to the socket the server is listening to.
def initialize(uri, socket_path)
@socket_path = socket_path
super(uri)
end
# Create the socket object.
def connect
@socket = Net::BufferedIO.new UNIXSocket.new socket_path
on_connect
end
# Override to prevent errors concatenating relative URI objects.
def addr_port
File.basename(socket_path)
end
end
end
###########################################################
# sock_party.rb, a ConnectionAdapter class
###########################################################
require "net/http"
require "socket"
class SockParty < HTTParty::ConnectionAdapter
# Override the base class connection method.
# Only difference is that we'll create a Net::SocketHttp rather than a Net::HTTP.
# Relies on :socket_path in the
def connection
http = Net::SocketHttp.new(uri, options[:socket_path])
if options[:timeout] && (options[:timeout].is_a?(Integer) || options[:timeout].is_a?(Float))
http.open_timeout = options[:timeout]
http.read_timeout = options[:timeout]
end
if options[:debug_output]
http.set_debug_output(options[:debug_output])
end
if options[:ciphers]
http.ciphers = options[:ciphers]
end
return http
end
end
###########################################################
# class MockSockParty, a really *nix-y HTTParty
###########################################################
class MockSockParty
include HTTParty
self.default_options = {connection_adapter: SockParty, socket_path: '/tmp/thin.sock'}
def party_hard
self.class.get('/client').body
end
end
###########################################################
# sock_party_spec.rb
###########################################################
require 'spec_helper'
describe SockParty do
it "should party until its socks fall off." do
puts MockSockParty.new.party_hard
end
end
由於其他人已經指出了不涉及編寫自己請求的替代方案,因此我會盡量總結您提出的請求出了什麼問題。 1:你的標題由'\ n'終止;它們實際上應該由'\ r \ n'終止。 2:以類似的方式,您應該使用'\ r \ n \ r \ n',而不是'\ n \ r \ n \ r'來終止您的請求。 3:每個服務器我都會在需要的時候拋出一個手寫的HTTP請求,甚至那些實際上並沒有給出它的值的東西 - 也就是'Host:localhost'的行'應該在你的情況下工作得很好。 – javawizard 2015-03-05 08:04:13