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
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.
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.
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With