Juanin
Juanin

Reputation: 91

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

Upvotes: 6

Views: 8852

Answers (2)

jcrossley3
jcrossley3

Reputation: 11764

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.

Upvotes: 5

mamills
mamills

Reputation: 1806

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

Upvotes: 2

Related Questions