Rails:带有 Net::HTTP 的 Cookie
我有两个 Rails 应用程序 App1 和 App2 ,它们都在不同的 URL 上运行,但在同一台计算机上。 App1 使用 Net::HTTP
从 App2 获取一些数据。我需要做的是当从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
请指教。
I have two rails applications App1 and App2 both running on separate URLs but on same machine. App1 fetch some data using Net::HTTP
from App2. What I need to do is to set a cookie
in App2 when request is made from App1. Currently, it's not setting the cookie. Do I need to add some header in App1 while sending request to App2, or what?
Here is the code to fetch the content:
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
Please advice.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
第一个问题:你想把cookie放在哪里?在浏览您网站的客户端上?
您的请求流程是否类似于:
客户端 --[网络浏览器]-->应用程序 1 --[net::http]--> App2
如果这是流程,您必须代理 cookie:
确保您需要 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
first question: Where do you want to place the cookie? On the client who is browsing your website?
Is your request flow like:
Client --[web browser]--> App 1 --[net::http]--> App2
If this is the flow, you have to proxy the cookie:
Make sure you require CGI::Cookie
Here are the docs:
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