### Install http.rb Manually Source: https://github.com/httprb/http/blob/main/README.md Install the http.rb gem directly using the gem command. ```bash $ gem install http ``` -------------------------------- ### Making an HTTP GET Request Source: https://github.com/httprb/http/wiki/Response-Handling Initiates an HTTP GET request to a specified URL and returns an HTTP::Response object. This is the starting point for handling server responses. ```ruby response = HTTP.get('https://www.google.com') ``` -------------------------------- ### Make a Simple GET Request (Response Body) Source: https://github.com/httprb/http/blob/main/README.md Perform a GET request to a URL and get the response body as a string. This is the simplest way to fetch content. ```ruby HTTP.get("https://github.com").to_s ``` -------------------------------- ### Install http.rb via Bundler Source: https://github.com/httprb/http/blob/main/README.md Execute this command in your terminal after adding the gem to your Gemfile. ```bash $ bundle ``` -------------------------------- ### Install http.rb Gem Source: https://github.com/httprb/http/blob/main/README.md Add this line to your application's Gemfile to include http.rb. ```ruby gem "http" ``` -------------------------------- ### Make a Simple GET Request (Response Object) Source: https://github.com/httprb/http/blob/main/README.md Perform a GET request and obtain the full HTTP::Response object. This allows access to status, headers, and body. ```ruby HTTP.get("https://github.com") ``` -------------------------------- ### Make a GET Request Source: https://github.com/httprb/http/wiki/Making-Requests Perform a GET request to a specified URL and receive an HTTP::Response object. ```ruby >> response = HTTP.get('https://www.google.com') => #"text/html; charset=UTF-8", "Date"=>"Fri, ...> ``` -------------------------------- ### Default HTTP.get request Source: https://github.com/httprb/http/wiki/Disabling-URI-Normalization This is the standard way to make a GET request. Use this when URI normalization is not causing issues. ```ruby ::HTTP.get('https://th.wiktionary.org/wiki/%E0%B8%84%E0%B8%B3') ``` -------------------------------- ### Perform GET Request with Shorthand Header Syntax Source: https://github.com/httprb/http/wiki/Headers A shorter alias for setting headers is available using bracket notation. This achieves the same result as the .headers method. ```ruby HTTP[:accept => "application/json"] .get("https://github.com/httprb/http/commit/HEAD") ``` -------------------------------- ### Follow Redirects and Get Final URI Source: https://github.com/httprb/http/wiki/Privacylity Use `HTTP.follow.get` to automatically follow redirects. The final URI after all redirects is accessible via `response.uri.to_s`. ```Ruby response = HTTP.follow.get("https://httpbin.org/redirect-to", params: { url: "https://httpbin.org/get" }) response.uri.to_s => "https://httpbin.org/get" ``` -------------------------------- ### Enable Automatic Redirect Following Source: https://github.com/httprb/http/wiki/Redirects Use `HTTP.follow` to automatically follow redirect responses. This is the default behavior for GET requests. ```ruby response = HTTP.follow .get("https://example.com") ``` -------------------------------- ### HTTP Caching with In-Memory Store Source: https://github.com/httprb/http/blob/main/UPGRADING.md Enable HTTP caching according to RFC 7234 by using `.use(:caching)`. This example uses the default in-memory store. ```ruby HTTP.use(:caching).get("https://example.com") # caches with in-memory store ``` -------------------------------- ### Perform GET Request with Accept Header Source: https://github.com/httprb/http/wiki/Headers Use the Accept header for proper content negotiation. This method explicitly tells the server the desired response format, such as JSON. ```ruby HTTP.headers(:accept => "application/json") .get("https://github.com/httprb/http/commit/HEAD") ``` -------------------------------- ### Perform GET Request with File Extension Source: https://github.com/httprb/http/wiki/Headers This method appends a file extension to the URL to request a specific format. It's a simpler approach but relies on the server supporting this convention. ```ruby HTTP.get("https://github.com/httprb/http/commit/HEAD.json") ``` -------------------------------- ### Pattern Matching on HTTP Response Source: https://github.com/httprb/http/blob/main/README.md Utilize Ruby's pattern matching to conditionally handle responses based on status code and body content. This example demonstrates matching successful responses, 404s, and other client errors. ```ruby case HTTP.get("https://api.example.com/users") in { status: 200..299, body: body } JSON.parse(body.to_s) in { status: 404 } nil in { status: 400.. } raise "request failed" end ``` -------------------------------- ### Add Query String Parameters to Requests Source: https://github.com/httprb/http/wiki/Passing-Parameters Use the `:params` option to append query string parameters to a GET request URL. ```ruby HTTP.get("http://example.com/resource", :params => {:foo => "bar"}) ``` -------------------------------- ### Get Response Body Source: https://github.com/httprb/http/wiki/Making-Requests Extract the response body as a string from the HTTP::Response object using the #to_s method. ```ruby >> response.to_s => "> response.code => 200 ``` -------------------------------- ### Get Final URL After Redirects Source: https://github.com/httprb/http/wiki/Redirects Access the final URL of a redirect chain using the `uri` method on the response object. This is useful for verifying the destination after redirects. ```ruby response = HTTP.follow.get("https://httpbin.org/redirect-to", params: { url: "https://httpbin.org/get" }) response.uri.to_s => "https://httpbin.org/get" ``` -------------------------------- ### Make Request with Basic Auth Source: https://github.com/httprb/http/wiki/Authorization-Header After setting up authorization using `#basic_auth`, you can proceed to make HTTP requests as usual. The authorization header will be included automatically. ```ruby HTTP.basic_auth(:user => "user", :pass => "pass") .get("https://example.com") ``` -------------------------------- ### Other HTTP Methods Source: https://github.com/httprb/http/wiki/Making-Requests Demonstrates making POST, PUT, PATCH, DELETE, and HEAD requests. ```ruby >> response = HTTP.post('https://restapi.com/objects') >> response = HTTP.put('https://restapi.com/put') >> response = HTTP.patch('https://restapi.com/put') >> response = HTTP.delete('https://restapi.com/put') >> response = HTTP.head('https://restapi.com/put') ``` -------------------------------- ### Configure TLS/SSL Options Source: https://github.com/httprb/http/wiki/Making-Requests Pass TLS/SSL options, such as verify_mode and ca_file, using the :ssl key for secure requests. ```ruby HTTP.post("வுகளை", ssl: {verify_mode: OpenSSL::SSL::VERIFY_PEER, ca_file: "/usr/local/etc/trusted-certificates.pem"}) ``` -------------------------------- ### Create HTTP Client with Persistent Connection Source: https://github.com/httprb/http/wiki/Persistent-Connections-(keep-alive) Create an HTTP client with a persistent connection to a specified host. Ensure to close the connection when it's no longer needed. ```ruby begin # create HTTP client with persistent connection to api.icndb.com: http = HTTP.persistent "http://api.icndb.com" # issue multiple requests using same connection: jokes = 100.times.map { http.get("/jokes/random").to_s } ensure # close underlying connection when you don't need it anymore http.close if http end ``` -------------------------------- ### Use Instrumentation with ActiveSupport::Notifications Source: https://github.com/httprb/http/wiki/Logging-and-Instrumentation Integrate with ActiveSupport::Notifications for advanced logging and instrumentation. Subscribe to 'start_request.http' events to receive notifications about outgoing requests. ```ruby ActiveSupport::Notifications.subscribe('start_request.http') do |name, start, finish, id, payload| pp :name => name, :start => start.to_f, :finish => finish.to_f, :id => id, :payload => payload end http = HTTP.use(instrumentation: { instrumenter: ActiveSupport::Notifications.instrumenter }) http.get("https://httpbin.org/get") ``` -------------------------------- ### Enable Logging by Default Source: https://github.com/httprb/http/wiki/Logging-and-Instrumentation Set default options to enable the logging feature for all HTTP clients. This applies the logger configuration globally. ```ruby HTTP.default_options = HTTP::Options.new(features: { logging: { logger: Logger.new(STDOUT) } }) ``` -------------------------------- ### Handle Cross-Origin Redirects Source: https://github.com/httprb/http/blob/main/README.md Use `HTTP.persistent.follow` to automatically handle redirects across different origins by establishing new persistent connections as needed. ```ruby HTTP.persistent("https://example.com").follow do |http| http.get("/moved-to-other-domain") # follows redirect across origins end ``` -------------------------------- ### Perform Basic Authentication Source: https://github.com/httprb/http/wiki/Authorization-Header Use the `#basic_auth` method with a username and password to perform HTTP Basic Authentication. This method constructs the `Authorization` header for you. ```ruby HTTP.basic_auth(:user => "user", :pass => "pass") # "Basic dXNlcjpwYXNz"}> ``` -------------------------------- ### Thread-Safe Connection Pooling with connection_pool Source: https://github.com/httprb/http/wiki/Thread-Safety Demonstrates how to use persistent connections with the 'connection_pool' gem to manage a thread-safe connection pool for concurrent HTTP requests. ```ruby require "http" require "connection_pool" pool = ConnectionPool.new(size: 5, timeout: 5) do HTTP.persistent("https://github.com") end # Fetch multiple paths concurrently threads = %w(/ruby /httprb /sparklemotion).map do |path| Thread.new do pool.with { |conn| conn.get(path).to_s } end end responses = threads.map(&:value) ``` -------------------------------- ### Use Logging Feature with a Logger Source: https://github.com/httprb/http/wiki/Logging-and-Instrumentation Configure the HTTP client to log requests and responses to a specified logger. Ensure the logger is initialized before use. ```ruby logger = Logger.new(STDOUT) http = HTTP.use(logging: {logger: logger}) http.get("https://httpbin.org/get") ``` -------------------------------- ### Build and Reuse HTTP Session Source: https://github.com/httprb/http/blob/main/README.md Configure a session once with headers, timeout, and authentication, then reuse it across multiple threads for consistent requests. ```ruby session = HTTP.headers("Accept" => "application/json") .timeout(10) .auth("Bearer token") threads = 10.times.map do Thread.new { session.get("https://example.com/api/data") } end threads.each(&:join) ``` -------------------------------- ### Using Client Certificates for HTTPS Source: https://github.com/httprb/http/wiki/HTTPS Pass a custom OpenSSL::SSL::SSLContext object to specify client certificates for authentication. Ensure your certificate and key files are correctly read. ```ruby HTTP.get("https://example.com", ssl_context: OpenSSL::SSL::SSLContext.new.tap do |ctx| ctx.set_params( cert: OpenSSL::X509::Certificate.new(File.read("client.crt")), key: OpenSSL::PKey::RSA.new(File.read("client.key")) ) end) ``` -------------------------------- ### Chainable Methods Return HTTP::Session (v5 vs v6) Source: https://github.com/httprb/http/blob/main/UPGRADING.md In v5, chainable methods returned HTTP::Client. In v6, they return HTTP::Session, which is thread-safe and creates a fresh Client for each request. Update any `is_a?(HTTP::Client)` checks accordingly. ```ruby client = HTTP.headers("Accept" => "application/json") client.is_a?(HTTP::Client) # => true ``` ```ruby session = HTTP.headers("Accept" => "application/json") session.is_a?(HTTP::Session) # => true session.get("https://example.com") # works the same ``` -------------------------------- ### Options Replaced with Keyword Arguments (v5 vs v6) Source: https://github.com/httprb/http/blob/main/UPGRADING.md HTTP.rb v6 requires keyword arguments for options, replacing the ability to pass an options hash as a positional argument. Use the double-splat operator (`**`) to pass existing option hashes. ```ruby # v5 — both work HTTP.get("https://example.com", body: "data") HTTP.get("https://example.com", {body: "data"}) opts = {body: "data", headers: {"Content-Type" => "text/plain"}} HTTP.get("https://example.com", opts) ``` ```ruby # v6 — keywords only HTTP.get("https://example.com", body: "data") opts = {body: "data", headers: {"Content-Type" => "text/plain"}} HTTP.get("https://example.com", **opts) # note the double-splat ``` ```ruby # v5 HTTP::Options.new({response: :body}) HTTP::Client.new({timeout_class: HTTP::Timeout::Global}) ``` ```ruby # v6 HTTP::Options.new(response: :body) HTTP::Client.new(timeout_class: HTTP::Timeout::Global) # If you have an options hash, use double-splat: opts = {response: :body} HTTP::Options.new(**opts) ``` -------------------------------- ### Building Requests with HTTP::Request::Builder Source: https://github.com/httprb/http/blob/main/UPGRADING.md The `build_request` method is removed in v6. Use `HTTP::Request::Builder` to construct requests, passing options to its constructor. ```ruby # v5 request = HTTP.build_request(:get, "https://example.com") request = HTTP.headers("Accept" => "application/json") .build_request(:post, "https://example.com", json: {name: "test"}) # v6 options = HTTP::Options.new(headers: {"Accept" => "application/json"}, json: {name: "test"}) builder = HTTP::Request::Builder.new(options) request = builder.build(:post, "https://example.com") ``` -------------------------------- ### Make Request Through Proxy with Custom Headers Source: https://github.com/httprb/http/wiki/Proxy-Support Pass custom headers, such as 'Proxy-Authorization', when connecting through a proxy. ```ruby HTTP.via("proxy-hostname.local", 8080, {"Proxy-Authorization" => "gh-token:asxkdmaojsdnakjnmf3iem3imdf2qoimo324"}) .get("http://example.com/resource") ``` -------------------------------- ### Require the http.rb Gem Source: https://github.com/httprb/http/wiki/Making-Requests Include the http.rb gem in your project before making any requests. ```ruby require 'http' ``` -------------------------------- ### HTTP::URI Constructor Changes in v6 Source: https://github.com/httprb/http/blob/main/UPGRADING.md In v6, `HTTP::URI.new` no longer accepts `Addressable::URI` objects. Use `HTTP::URI.parse` instead. ```ruby # v5 addr = Addressable::URI.parse("https://example.com") HTTP::URI.new(addr) # works # v6 HTTP::URI.new(addr) # ArgumentError HTTP::URI.parse("https://example.com") # use parse instead ``` -------------------------------- ### Setting Base URI with HTTP.base_uri Source: https://github.com/httprb/http/blob/main/UPGRADING.md Use `HTTP.base_uri` to set a base URI for subsequent relative path requests. ```ruby api = HTTP.base_uri("https://api.example.com/v1") api.get("users") # GET https://api.example.com/v1/users api.get("posts") # GET https://api.example.com/v1/posts ``` -------------------------------- ### Making HTTPS Requests Source: https://github.com/httprb/http/wiki/HTTPS To make HTTPS requests, simply use an 'https://' prefixed URL. No special configuration is needed beyond what OpenSSL provides. -------------------------------- ### Combining Global and Per-Operation Timeouts in v6 Source: https://github.com/httprb/http/blob/main/UPGRADING.md v6 allows combining global timeouts with per-operation timeouts, unlike v5 which treated them as mutually exclusive. ```ruby # v5 — mutually exclusive, raises ArgumentError HTTP.timeout(global: 60, read: 30) # v6 — works: 60s overall, 30s max per read, 10s max per write, 5s max per connect HTTP.timeout(global: 60, read: 30, write: 10, connect: 5) ``` -------------------------------- ### Set Base URI for Requests Source: https://github.com/httprb/http/blob/main/README.md Configure a base URI to simplify subsequent requests by avoiding repetition of the scheme and host. Relative paths are resolved according to RFC 3986. ```ruby api = HTTP.base_uri("https://api.example.com/v1") api.get("users") # GET https://api.example.com/v1/users api.get("users/1") # GET https://api.example.com/v1/users/1 ``` -------------------------------- ### Persistent Connections with Base URI Source: https://github.com/httprb/http/blob/main/README.md Combine `base_uri` with `persistent` to reuse the same underlying connection for multiple requests to the same host. This is efficient for sequential operations. ```ruby HTTP.base_uri("https://api.example.com/v1").persistent do |http| http.get("users") http.get("posts") end ``` -------------------------------- ### Automatically Compress Request Body with Deflate Source: https://github.com/httprb/http/wiki/Compression Configure `:auto_deflate` to use the `:deflate` method for compressing the request body instead of the default gzip. ```ruby response = HTTP.use(:auto_deflate => {:method => :deflate}) .post("http://example.org/upload", body: body) ``` -------------------------------- ### Make Request Through Proxy Source: https://github.com/httprb/http/wiki/Proxy-Support Specify the proxy server's hostname and port to route requests through it. ```ruby HTTP.via("proxy-hostname.local", 8080) .get("http://example.com/resource") ``` -------------------------------- ### Add Raw Authorization Header Source: https://github.com/httprb/http/wiki/Authorization-Header Use the `#auth` method to pass a raw authorization header string. This is useful for schemes other than Basic Authentication. ```ruby HTTP.auth("Bearer VGhlIEhUVFAgR2VtLCBST0NLUw") # "Bearer VGhlIEhUVFAgR2VtLCBST0NLUw"}> ``` -------------------------------- ### Upload Files as Raw Request Body Source: https://github.com/httprb/http/wiki/Passing-Parameters Pass an opened file object directly as the request body to upload files in raw format. ```ruby HTTP.post("http://example.com/resource", body: File.open("/home/ixit/avatar.png")) ``` -------------------------------- ### Use Registered Custom Feature Source: https://github.com/httprb/http/wiki/Logging-and-Instrumentation Apply a custom feature to an HTTP client instance after it has been registered. ```ruby http = HTTP.use(:my_feature) ``` -------------------------------- ### Automatically Compress Request Body with Gzip Source: https://github.com/httprb/http/wiki/Compression Use the `:auto_deflate` option to automatically compress the request body. Gzip encoding is used by default. ```ruby response = HTTP.use(:auto_deflate) .post("http://example.org/upload", body: body) ``` -------------------------------- ### Reading Response Body as String Source: https://github.com/httprb/http/wiki/Response-Handling Retrieves the entire response body as a single string. Useful for simple responses or when the full content is needed immediately. ```ruby response.body.to_s ``` -------------------------------- ### HTTP.persistent Returns HTTP::Session with Connection Pooling (v5 vs v6) Source: https://github.com/httprb/http/blob/main/UPGRADING.md v5's `HTTP.persistent` returned `HTTP::Client`, which could lead to `StateError` on cross-origin redirects. v6 returns `HTTP::Session`, pooling clients per origin and enabling automatic cross-origin redirect handling. Chaining on a persistent session now correctly shares the connection pool. ```ruby client = HTTP.persistent("https://api.example.com") client.is_a?(HTTP::Client) # => true # Cross-origin redirects raise StateError ``` ```ruby session = HTTP.persistent("https://api.example.com") session.is_a?(HTTP::Session) # => true # Cross-origin redirects work — each origin gets its own connection session.close # shuts down all pooled connections ``` ```ruby # v5 — this broke connection reuse HTTP.persistent("https://api.example.com").headers("X-Token" => "abc").get("/users") # v6 — works correctly, shares the parent's connection pool HTTP.persistent("https://api.example.com").headers("X-Token" => "abc").get("/users") ``` -------------------------------- ### Register Custom Feature Source: https://github.com/httprb/http/wiki/Logging-and-Instrumentation Implement a custom feature by defining a class that adheres to the HTTP::Feature interface and registering it with the HTTP library. ```ruby HTTP::Options.register_feature(:my_feature, MyFeature) ``` -------------------------------- ### Upload Files via Form Data Source: https://github.com/httprb/http/wiki/Passing-Parameters Construct the form data with `HTTP::FormData::File` to upload files in multipart format. ```ruby HTTP.post("http://example.com/resource", :form => { :username => "ixti", :avatar => HTTP::FormData::File.new("/home/ixit/avatar.png") }) ``` -------------------------------- ### Handling Query Parameters in HTTP.rb v6 Source: https://github.com/httprb/http/blob/main/UPGRADING.md The `query_values` and `query_values=` methods are removed in v6. Use `URI.encode_www_form` for query string construction or the `params` option for requests. ```ruby # v5 uri.query_values = {"page" => "1", "per" => "10"} uri.query_values # => {"page" => "1", "per" => "10"} # v6 — use stdlib uri = HTTP::URI.parse("https://example.com") query = URI.encode_www_form(page: 1, per: 10) uri = HTTP::URI.parse("https://example.com?#{query}") # or use the params option: HTTP.get("https://example.com", params: {page: 1, per: 10}) ``` -------------------------------- ### Setting Explicit Per-Operation Timeouts Source: https://github.com/httprb/http/blob/main/UPGRADING.md In v6, omitted per-operation timeouts (read, write, connect) default to no limit. Explicitly set them if you relied on the v5 default of 0.25s. ```ruby # v5 — omitted operations default to 0.25s HTTP.timeout(read: 30).get(url) # write and connect timeouts are 0.25s # v6 — omitted operations have no timeout HTTP.timeout(read: 30).get(url) # write and connect have no timeout limit # Action: If you relied on the implicit 0.25s timeout, set all three operations explicitly: HTTP.timeout(read: 0.25, write: 0.25, connect: 0.25).get(url) ``` -------------------------------- ### Response::Status Object Usage Source: https://github.com/httprb/http/blob/main/UPGRADING.md In v6, `Response::Status` no longer delegates to `Integer`. Use `status.code.` for Integer methods and direct predicates like `ok?` or `success?`. ```ruby status = response.status # Still works in v6 status.to_i # => 200 status == 200 # => true (via Comparable + to_int) (200..299).cover?(status) # => true (via to_int) status.ok? # => true status.success? # => true status.to_s # => "200 OK" status.code # => 200 status.reason # => "OK" # v5 only — breaks in v6 status.even? # NoMethodError — use status.code.even? status.between?(200, 299) # NoMethodError — use status.code.between?(200, 299) status + 1 # NoMethodError — use status.code + 1 status.__getobj__ # NoMethodError — use status.code ``` -------------------------------- ### Thread-Safe Persistent Connections with ConnectionPool Source: https://github.com/httprb/http/blob/main/README.md Use the `connection_pool` gem to manage a pool of persistent HTTP clients for thread-safe access to a single origin. ```ruby pool = ConnectionPool.new(size: 5) { HTTP.persistent("https://example.com") } pool.with { |http| http.get("/path") } ``` -------------------------------- ### Configure Per-Operation Timeouts in HTTP Gem Source: https://github.com/httprb/http/wiki/Timeouts Enables per-operation timeouts for connect, write, and read phases of an HTTP request. Useful for fine-grained control over each network operation. ```ruby HTTP.timeout(connect: 5, write: 2, read: 10).get "http://example.com" ``` -------------------------------- ### Make Request Through Authenticated Proxy Source: https://github.com/httprb/http/wiki/Proxy-Support Provide username and password when the proxy server requires authentication. ```ruby HTTP.via("proxy-hostname.local", 8080, "username", "password") .get("http://example.com/resource") ``` -------------------------------- ### Retrieving Cookie Jar from Response Source: https://github.com/httprb/http/wiki/Cookies Obtain the cookie jar from a response to inspect or reuse cookies in subsequent requests. This utilizes the sparklemotion/http-cookie library. ```ruby response = HTTP.get("https://www.google.com") response.cookies ``` -------------------------------- ### Handling Multiple Certificates in a PEM File Source: https://github.com/httprb/http/wiki/HTTPS When a PEM file contains multiple certificates, parse them individually and assign the root certificate to 'cert' and intermediate certificates to 'extra_chain_cert' in the SSL context. ```ruby bundle = File.read("path_to_your_fullchain.pem") certificate_content_regex = /-----BEGIN CERTIFICATE-----(?:.|\n)+?-----END CERTIFICATE-----/ certs = bundle.scan(certificate_content_regex).map { OpenSSL::X509::Certificate.new(_1) } ssl_context = OpenSSL::SSL::SSLContext.new.tap do |ctx| ctx.set_params( cert: certs.shift, # The root certificate key: OpenSSL::PKey::RSA.new(File.read("path_to_your_private_key.pem")), extra_chain_cert: certs # The intermediate certificates ) end HTTP.get("https://example.com", ssl_context: ssl_context) ``` -------------------------------- ### Accessing HTTP Status Code and Reason Source: https://github.com/httprb/http/wiki/Response-Handling Retrieves the numerical status code, its corresponding reason phrase, or a combined string representation. Useful for logging or detailed error handling. ```ruby response.status #=> eg 500 response.status.reason #=> eg "Internal Server Error" response.status.to_s #=> eg "500 Internal Server Error" ``` -------------------------------- ### Access Headers on Request/Response Objects Source: https://github.com/httprb/http/blob/main/UPGRADING.md In v6, use `.headers` to access headers on Request and Response objects instead of direct bracket access. ```ruby # v5 response = HTTP.get("https://example.com") response["Content-Type"] # => "text/html" request["Authorization"] = "Bearer token" # v6 response = HTTP.get("https://example.com") response.headers["Content-Type"] # => "text/html" request.headers["Authorization"] = "Bearer token" ``` -------------------------------- ### Send Raw Request Bodies Source: https://github.com/httprb/http/wiki/Passing-Parameters Use the `:body` option to send a raw request body. This can be a String, Enumerable, or IO-like object for streaming. ```ruby HTTP.post("http://example.com/resource", :body => "foo=42&bar=baz") ``` -------------------------------- ### Passing Cookies in a Request Source: https://github.com/httprb/http/wiki/Cookies Configure cookies for a specific request using the `:cookies` option. This is useful for authenticating or maintaining session state. ```ruby response = HTTP.cookies(:session_cookie => "dXNlcl9pZD0xO21hYz1iY2NlYT...") .get("https://www.example.com") ``` -------------------------------- ### Configure Global Timeout in HTTP Gem Source: https://github.com/httprb/http/wiki/Timeouts Sets a global timeout for the entire HTTP request duration. This is an alternative to using `Timeout.timeout` for simpler overall request time limits. ```ruby HTTP.timeout(3).get "http://example.com" ``` -------------------------------- ### Require http.rb in Ruby Source: https://github.com/httprb/http/blob/main/README.md Include the http.rb library in your Ruby program to use its functionalities. ```ruby require "http" ``` -------------------------------- ### Customize Instrumentation Namespace Source: https://github.com/httprb/http/wiki/Logging-and-Instrumentation Specify a custom namespace for instrumentation events. This allows for better organization and filtering of notifications. ```ruby HTTP.use(instrumentation: { instrumenter: ActiveSupport::Notifications.instrumenter, namespace: "my_http" }) ``` -------------------------------- ### HTTP PURGE Method Source: https://github.com/httprb/http/blob/main/UPGRADING.md Make an HTTP `PURGE` request using `HTTP.request` with the `:purge` symbol. ```ruby HTTP.request(:purge, "https://cdn.example.com/asset") ``` -------------------------------- ### Streaming Response Body with #each Source: https://github.com/httprb/http/wiki/Response-Handling Processes the response body by iterating over chunks. This is memory-efficient for large responses. ```ruby response.body.each { |chunk| ... } ``` -------------------------------- ### Block Form for Verb Methods in HTTP.rb Source: https://github.com/httprb/http/blob/main/UPGRADING.md Use the block form for HTTP verb methods (e.g., `HTTP.get`) to automatically close the connection after the block executes. ```ruby body = HTTP.get("https://example.com") do |response| response.body.to_s end ``` -------------------------------- ### HTTP Timeout Options Parsing in v6 Source: https://github.com/httprb/http/blob/main/UPGRADING.md v6 enforces stricter parsing for timeout options, rejecting unknown keys and mixed short/long forms. Use either `read_timeout` or `read` consistently. ```ruby # v6 — rejects unknown keys HTTP.timeout(read: 5, keep_alive: 10) # => ArgumentError: unknown timeout options: keep_alive # v6 — rejects mixed short/long forms HTTP.timeout(read: 5, write_timeout: 3) # => ArgumentError (use one form consistently) # Valid in v6 HTTP.timeout(read: 5, write: 3, connect: 2) HTTP.timeout(read_timeout: 5, write_timeout: 3, connect_timeout: 2) ``` -------------------------------- ### Flush Response for Persistent Connections Source: https://github.com/httprb/http/wiki/Persistent-Connections-(keep-alive) When using persistent connections, ensure responses are consumed before the next request. Use `#to_s` or `#flush` to read the response body and free the connection. ```ruby contents = HTTP.persistent "http://en.wikipedia.org" do |http| %w(Hypertext_Transfer_Protocol Git GitHub Linux Hurd).map do |page| http.get("/wiki/#{page}").flush end end ``` -------------------------------- ### Pattern Matching on HTTP Responses Source: https://github.com/httprb/http/blob/main/UPGRADING.md Utilize Ruby's pattern matching to conditionally handle responses based on status code and content type. ```ruby case response in { status: { code: 200..299 }, content_type: { mime_type: "application/json" } } response.parse in { status: { code: 404 } } nil end ``` -------------------------------- ### Response Cookies Return Array Instead of CookieJar Source: https://github.com/httprb/http/blob/main/UPGRADING.md In v6, `response.cookies` returns an Array of `HTTP::Cookie` objects. Direct lookup on the result is no longer supported; use Array methods like `find`. ```ruby # v5 response.cookies # => # response.cookies.each { |cookie| puts cookie.name } jar = response.cookies jar["session_id"] # CookieJar lookup # v6 response.cookies # => [#, ...] response.cookies.each { |cookie| puts cookie.name } cookie = response.cookies.find { |c| c.name == "session_id" } ``` -------------------------------- ### HTTP::URI Return Type for join/omit Source: https://github.com/httprb/http/blob/main/UPGRADING.md The `join` and `omit` methods now return `HTTP::URI` objects in v6, unlike v5 which returned `Addressable::URI`. ```ruby # v5 uri = HTTP::URI.parse("https://example.com") joined = uri.join("/path") joined.is_a?(Addressable::URI) # => true # v6 joined = uri.join("/path") joined.is_a?(HTTP::URI) # => true ``` -------------------------------- ### Automatically Decompress Response Body Source: https://github.com/httprb/http/wiki/Compression Use the `:auto_inflate` option to automatically decompress the response body. Ensure the 'Accept-Encoding' header is set to 'gzip' or other supported encodings. ```ruby response = HTTP.use(:auto_inflate).headers("Accept-Encoding" => "gzip") .get("http://example.org/large-file") ``` -------------------------------- ### Pass Form Data in POST Requests Source: https://github.com/httprb/http/wiki/Passing-Parameters Use the `:form` option to send data serialized as form-encoded in a POST request. ```ruby HTTP.post("http://example.com/resource", :form => {:foo => "42"}) ``` -------------------------------- ### Stream Response Body Source: https://github.com/httprb/http/blob/main/README.md Read the response body in chunks using `readpartial`. Assign the body to a local variable and repeatedly call `readpartial` until it returns nil. ```ruby body = HTTP.get("https://github.com").body body.readpartial body.readpartial # ... body.readpartial => nil ``` -------------------------------- ### Form Encoding in HTTP.rb v6 Source: https://github.com/httprb/http/blob/main/UPGRADING.md The `HTTP::URI.form_encode` method has been removed. Use the standard library's `URI.encode_www_form` instead. ```ruby # v5 HTTP::URI.form_encode(page: 1, per: 10) # v6 URI.encode_www_form(page: 1, per: 10) ``` -------------------------------- ### Use Persistent Connection with a Block Source: https://github.com/httprb/http/wiki/Persistent-Connections-(keep-alive) Utilize a persistent connection within a block, where the connection is automatically closed upon block termination. The block's return value is the result of the operation. ```ruby jokes = HTTP.persistent "http://api.icndb.com" do |http| 100.times.map { http.get("/jokes/random").to_s } end ``` -------------------------------- ### Reading Response Body Partially Source: https://github.com/httprb/http/wiki/Response-Handling Reads a portion of the response body at a time. Useful for processing large bodies incrementally without loading the entire content into memory. ```ruby response.body.readpartial ``` -------------------------------- ### Serialize Ruby Objects as JSON Source: https://github.com/httprb/http/wiki/Passing-Parameters Use the `:json` option to automatically serialize Ruby objects into a JSON request body for POST requests. ```ruby HTTP.post("http://example.com/resource", :json => { :foo => "42" }) ``` -------------------------------- ### Limit Number of Redirects Source: https://github.com/httprb/http/wiki/Redirects Control the maximum number of redirects allowed using the `:max_hops` option. Exceeding this limit will raise an `HTTP::Redirector::TooManyRedirectsError`. ```ruby response = HTTP.follow(max_hops: 3) .get("https://example.com") ``` -------------------------------- ### Malformed URI Error Handling in HTTP.rb v6 Source: https://github.com/httprb/http/blob/main/UPGRADING.md HTTP.rb v6 introduces `HTTP::URI::InvalidError` for malformed URIs and `ArgumentError` for nil/empty URIs, replacing v5's `HTTP::UnsupportedSchemeError` or `Addressable::URI::InvalidURIError`. ```ruby # v5 HTTP.get("not a uri") # => HTTP::UnsupportedSchemeError or Addressable::URI::InvalidURIError # v6 HTTP.get("not a uri") # => HTTP::URI::InvalidError (for malformed URIs) HTTP.get(nil) # => ArgumentError (for nil/empty URIs) ``` -------------------------------- ### Retriable Operations Return HTTP::Session (v5 vs v6) Source: https://github.com/httprb/http/blob/main/UPGRADING.md In v5, `.retriable` returned `HTTP::Retriable::Client`. In v6, retry functionality is a session-level option, and `.retriable` now returns `HTTP::Session`. The `HTTP::Retriable::Client` and `HTTP::Retriable::Session` classes are removed. ```ruby client = HTTP.retriable(tries: 3) client.is_a?(HTTP::Retriable::Client) # => true ``` ```ruby session = HTTP.retriable(tries: 3) session.is_a?(HTTP::Session) # => true session.get("https://example.com") # retries up to 3 times ``` -------------------------------- ### HTTP.get request with disabled URI normalization Source: https://github.com/httprb/http/wiki/Disabling-URI-Normalization Use this method to explicitly disable URI normalization by providing a custom normalizer that uses HTTP::URI.parse. This can resolve 404 errors caused by faulty URI handling of Unicode characters. ```ruby ::HTTP.use({ normalize_uri: { normalizer: ->(uri) { HTTP::URI.parse(uri) }, }, }).get( 'https://th.wiktionary.org/wiki/%E0%B8%84%E0%B8%B3' ) ``` -------------------------------- ### HTTP Digest Authentication Source: https://github.com/httprb/http/blob/main/UPGRADING.md Perform HTTP Digest Authentication by chaining `.digest_auth` with user credentials. ```ruby HTTP.digest_auth(user: "admin", pass: "secret").get("https://example.com/protected") ``` -------------------------------- ### Checking HTTP Status Codes Source: https://github.com/httprb/http/wiki/Response-Handling Provides boolean methods to check the category of the HTTP status code (e.g., informational, success, client error). Use these to determine the outcome of the request. ```ruby response.status.informational? # 1xx response.status.success? # 2XX response.status.redirect? # 3xx response.status.client_error? # 4XX response.status.server_error? # 5XX ``` -------------------------------- ### Immutable URI Objects in HTTP.rb v6 Source: https://github.com/httprb/http/blob/main/UPGRADING.md In v6, URI objects are immutable. Construct a new URI instead of modifying existing ones. ```ruby # v5 uri = HTTP::URI.parse("https://example.com") uri.scheme = "http" uri.path = "/api" # v6 — construct a new URI instead uri = HTTP::URI.parse("http://example.com/api") ``` -------------------------------- ### Disabling Certificate Verification (Insecure) Source: https://github.com/httprb/http/wiki/HTTPS To disable certificate verification, set the verify_mode of an OpenSSL::SSL::SSLContext to OpenSSL::SSL::VERIFY_NONE. This is highly insecure and should be avoided. ```ruby ctx = OpenSSL::SSL::SSLContext.new ctx.verify_mode = OpenSSL::SSL::VERIFY_NONE HTTP.get("https://www.google.com", :ssl_context => ctx) ``` -------------------------------- ### Specific ConnectionError Subclasses in HTTP.rb v6 Source: https://github.com/httprb/http/blob/main/UPGRADING.md v6 introduces specific subclasses for `ConnectionError` like `HTTP::ResponseHeaderError`, `HTTP::SocketReadError`, and `HTTP::SocketWriteError` for more targeted error handling. ```ruby # v5 rescue HTTP::ConnectionError => e # all connection errors # v6 — you can be more specific rescue HTTP::SocketReadError => e # only read failures rescue HTTP::ConnectionError => e # still catches all connection errors (superclass) ``` -------------------------------- ### Access Response Body Object Source: https://github.com/httprb/http/blob/main/README.md Retrieve the HTTP::Response::Body object from a response. This object is used for streaming the response content. ```ruby HTTP.get("https://github.com").body ``` -------------------------------- ### Lazy Loading of Addressable Gem Source: https://github.com/httprb/http/blob/main/UPGRADING.md The `addressable` gem is no longer a runtime dependency in v6. It is lazy-loaded only when parsing non-ASCII (IRI) URIs. Add `addressable` to your Gemfile if your code uses such URIs. ```ruby # Add to Gemfile if using non-ASCII URIs: gem "addressable" ``` -------------------------------- ### HTTP Cookies Chainable Option Behavior Source: https://github.com/httprb/http/blob/main/UPGRADING.md The `cookies` chainable option in v6 no longer merges cookies across calls; the last call to `cookies()` determines the set of cookies sent. ```ruby # v5 — cookies merged across calls HTTP.cookies(a: "1").cookies(b: "2") # sends both a=1 and b=2 # v6 — last call wins HTTP.cookies(a: "1").cookies(b: "2") # sends only b=2 HTTP.cookies(a: "1", b: "2") # sends both a=1 and b=2 ``` -------------------------------- ### Handling EOFError with readpartial Source: https://github.com/httprb/http/blob/main/UPGRADING.md In v6, `readpartial` on response bodies raises `EOFError` at end-of-stream instead of returning `nil`. The `each` iterator remains compatible. ```ruby # v5 loop do chunk = response.body.readpartial break if chunk.nil? process(chunk) end # v6 loop do chunk = response.body.readpartial process(chunk) rescue EOFError break end # Or use the simpler iterator API (works in both versions): response.body.each { |chunk| process(chunk) } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.