如何在Ruby Net :: HTTP中实现cookie

时间:2022-09-02 13:29:38

That's my code.

那是我的代码。

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

现在我需要向主机发送cookie但我找不到解决方案。


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

2 个解决方案

#1


5  

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

您通过发送“Accept-Language”标题的相同哈希传递Cookie,例如:

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.

但是,您可能需要首先捕获cookie。有关cookie处理的示例,请参阅此处。

#2


2  

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.

您需要首先从服务器的响应的“set-cookie”标头字段中检索服务器中的cookie。在您检索到cookie之后,您可以在客户端的请求的“cookie”标题中传递它们。

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

这个问题已经在如何在ruby net / http中实现cookie支持了?

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

接受的答案很好,除非您的服务器返回一组cookie,在这种情况下您可能需要查看https://*.com/a/9320190/1024480

#1


5  

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

您通过发送“Accept-Language”标题的相同哈希传递Cookie,例如:

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.

但是,您可能需要首先捕获cookie。有关cookie处理的示例,请参阅此处。

#2


2  

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.

您需要首先从服务器的响应的“set-cookie”标头字段中检索服务器中的cookie。在您检索到cookie之后,您可以在客户端的请求的“cookie”标题中传递它们。

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

这个问题已经在如何在ruby net / http中实现cookie支持了?

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

接受的答案很好,除非您的服务器返回一组cookie,在这种情况下您可能需要查看https://*.com/a/9320190/1024480