Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to implement cookies in Ruby Net::HTTP

That's my code.

Now I need to SEND a cookie to the host but I can't find a solution.


def get_network_file(url=nil)
  begin
    http = Net::HTTP.new( @service_server, 80 )
    resp, data = http.get( url, { "Accept-Language" => @locale } )
    if resp.code.to_i != 200
      RAILS_DEFAULT_LOGGER.error "*** return code != 200. code = #{resp.code}"
      return ""
    end
    rescue Exception => exc
      RAILS_DEFAULT_LOGGER.error "*** message --> #{exc.message}"
      return ""
    end
    return data
  end
end

like image 754
Juanin Avatar asked Aug 04 '10 17:08

Juanin


People also ask

How do I add cookies to my HTTP request?

To add cookies to a request for authentication, use the header object that is passed to the get/sendRequest functions. Only the cookie name and value should be set this way. The other pieces of the cookie (domain, path, and so on) are set automatically based on the URL the request is made against.

How do I send a cookie in HTTP header?

To send cookies to the server, you need to add the "Cookie: name=value" header to your request. To send multiple Cookies in one cookie header, you can separate them with semicolons. In this Send Cookies example, we are sending HTTP cookies to the ReqBin echo URL.

How are cookies sent in HTTP?

The Set-Cookie header is sent by the server in response to an HTTP request, which is used to create a cookie on the user's system. The Cookie header is included by the client application with an HTTP request sent to a server, if there is a cookie that has a matching domain and path.

What is cookie in HTTP header?

A cookie is an HTTP request header i.e. used in the requests sent by the user to the server. It contains the cookies previously sent by the server using one or more set-cookie headers. It is an optional header.


2 Answers

You pass cookies via the same hash you're sending the "Accept-Language" header, something like:

resp, data = http.get( url, { 
     "Accept-Language" => @locale, 
     "Cookie" => "YOUR_COOKIE" 
} )

Odds are you'll need to capture the cookie first, though. See this for examples of cookie handling.

like image 89
jcrossley3 Avatar answered Sep 28 '22 07:09

jcrossley3


You need to first retrieve the cookie(s) from your server from the server's response's "set-cookie" header field(s). After you've retrieved the cookie(s) then you pass it/them in your client's request's "cookie" header.

This question is asked already at How to implement cookie support in ruby net/http?

The accepted answer there is fine unless your server returns a set of cookies in which case you may want to look at https://stackoverflow.com/a/9320190/1024480

like image 45
mamills Avatar answered Sep 28 '22 07:09

mamills