【问题标题】:Rails: Cookies with Net::HTTPRails:带有 Net::HTTP 的 Cookie
【发布时间】:2011-10-13 11:12:09
【问题描述】:

我有两个 Rails 应用程序 App1App2 都在不同的 URL 上但在同一台机器上运行。 App1 使用来自 App2Net::HTTP 获取一些数据。当 App1 发出请求时,我需要做的是在 App2 中设置 cookie。目前,它没有设置cookie。向 App2 发送请求时,是否需要在 App1 中添加一些标头?

这里是获取内容的代码:

def get_content(url)

    uri = URI.parse(url)

    params = Hash[*uri.query.split("&").map {|part| part.split("=") }.flatten]

    http = Net::HTTP.new(uri.host, uri.port)
    request = Net::HTTP::Get.new(uri.path)
    request.set_form_data( params )
    request = Net::HTTP::Get.new( uri.path+ '?' + request.body )

    if uri.scheme == "https"  # enable SSL/TLS
      http.use_ssl = true
      http.verify_mode = OpenSSL::SSL::VERIFY_NONE
    end
    http.start do
      http.request(request) do|res|
        return res.body
      end
    end
end

请指教。

【问题讨论】:

  • 我认为,可能是错误的,由于您正在执行直接 http 请求,因此您必须自己管理标头中的 cookie。
  • 好的,但是我自己怎么做呢?任何例子将不胜感激。谢谢。

标签: ruby-on-rails cookies cross-domain


【解决方案1】:

第一个问题:你想把 cookie 放在哪里?在浏览您网站的客户端上?

您的请求流程是这样的吗:

客户端 --[网络浏览器]--> App 1 --[net::http]--> App2

如果这是流程,则必须代理 cookie:

def get_content(url)

    uri = URI.parse(url)

    params = Hash[*uri.query.split("&").map {|part| part.split("=") }.flatten]

    http = Net::HTTP.new(uri.host, uri.port)
    request = Net::HTTP::Get.new(uri.path)
    request.set_form_data( params )
    request = Net::HTTP::Get.new( uri.path+ '?' + request.body )

    if uri.scheme == "https"  # enable SSL/TLS
      http.use_ssl = true
      http.verify_mode = OpenSSL::SSL::VERIFY_NONE
    end
    http.start do
      http.request(request) do |res|
        # yummy, parse some cookies here
        app2_cookies  = CGI::Cookie.parse(res['Set-Cookie']);

        app2_cookies.each do |c_name, c_cookie|
          # this is the cookies object from rails! Make sure this is accessible here!
          # the cookie will now be set on the client side
          cookies[c_name] = c_cookie.value
        end

        return res.body
      end
    end
end

确保您需要 CGI::Cookie

这里是文档:

http://www.ruby-doc.org/stdlib/libdoc/net/http/rdoc/classes/Net/HTTPHeader.html#M001307

http://ruby-doc.org/stdlib/libdoc/cgi/rdoc/classes/CGI/Cookie.html#M000170

【讨论】:

  • 谢谢雪橇。我真的很感谢你的努力。我会试一试,然后告诉你结果。
  • 虽然它设置了 cookie,但设置了 App1 从哪里发出请求。我需要从 App2 设置和访问 cookie。你能指导我吗?
  • app2 没有直接连接到网络浏览器,不能直接设置cookie。如果 App2 在不同的 上运行,则由于安全限制,无法直接执行此操作。如果是这种情况,您需要使用 Net::Http 从 App2 向 App1 发出代理请求。
  • App1 和 App2 在不同的域下运行。
  • 我的截止日期很紧。如果你能帮我解决这个问题,我将不胜感激。再次感谢。
猜你喜欢
  • 2019-03-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-08-21
  • 2012-05-20
  • 2011-10-21
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多