14.3. Dostosowywanie nagłówków żądań HTTP

Problem

Podczas tworzenia żądania HTTP chcemy zdefiniować własne nagłówki HTTP, na przykład "User-Agent" lub "Accept-Language".

Rozwiązanie

Należy przekazać hasz z wartościami nagłówków do metod Net::HTTP#get lub Net::HTTP#post:

require 'net/http' require 'uri' # Prosta metoda opakowująca, która pobiera łańcuchy lub obiekty URI # i wykonuje żądanie HTTP GET. module Net class HTTP def HTTP.get_with_headers(uri, headers=nil) uri = URI.parse(uri) if uri.respond_to? :to_str start(uri.host, uri.port) do |http| path_query = uri.path + (uri.query ? ('?' + uri.query) : '') return http.get(path_query, headers) end end end end #Pobranie strony WWW w języku niemieckim. res = Net::HTTP.get_with_headers('http://www.google.com/', ...

Get Ruby. Receptury now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.