乐闻世界logo
搜索文章和话题

How to implement cookie support in ruby net/ http ?

1个答案

1

By default, the net/http library in Ruby does not natively support handling cookies when making HTTP requests. To implement cookie support, you need to manually process the Set-Cookie header sent by the server and include these cookies in subsequent requests. Below are the steps and example code to achieve this:

Step 1: Send Initial Request and Capture Cookies

First, send an HTTP request to the server and capture the Set-Cookie header from the response.

ruby
require 'net/http' require 'uri' uri = URI('http://example.com/login') response = Net::HTTP.get_response(uri) # Initialize cookie storage cookies = [] if response['Set-Cookie'] cookies << response['Set-Cookie'].split('; ')[0] end

Here, we store the cookies sent by the server in an array. Note that the server may send multiple Set-Cookie headers, so you may need more complex handling to capture all cookies.

Step 2: Send Cookies in Subsequent Requests

After capturing the cookies, include them in the request headers for subsequent requests.

ruby
uri = URI('http://example.com/data') http = Net::HTTP.new(uri.host, uri.port) # Create an HTTP request request = Net::HTTP::Get.new(uri.request_uri) # Add cookies to the request header request['Cookie'] = cookies.join('; ') # Send the request response = http.request(request) puts response.body

In this example, we create a new GET request and include the previously stored cookies in the request headers before sending the request.

Encapsulate into a Method

To facilitate reuse and management, encapsulate the cookie handling logic into a class or method.

ruby
class SimpleCookieClient attr_accessor :cookies def initialize @cookies = [] end def fetch(uri, method = :get) uri = URI(uri) http = Net::HTTP.new(uri.host, uri.port) request = Net::HTTP::Get.new(uri.request_uri) if method == :get # Add cookies to the request request['Cookie'] = cookies.join('; ') unless cookies.empty? response = http.request(request) # Store cookies from response response.get_fields('set-cookie').each do |value| cookies << value.split('; ')[0] end if response.get_fields('set-cookie') response end end # Usage example client = SimpleCookieClient.new response = client.fetch('http://example.com/login') puts response.body response = client.fetch('http://example.com/data') puts response.body

In this class, we use an instance variable @cookies to store cookies. The fetch method handles sending requests and automatically manages cookie storage and sending.

Summary

By following the above steps and code examples, you can handle cookies in HTTP requests using Ruby's net/http library without third-party libraries. This is particularly useful for simple scripts or learning basic HTTP protocol handling. For more complex HTTP client applications, consider using libraries that support features like cookies and redirects, such as rest-client or httparty.

2024年8月12日 12:45 回复

你的答案