Ruby Net::HTTP - 跟随 301 重定向 [英] Ruby Net::HTTP - following 301 redirects

查看:45
本文介绍了Ruby Net::HTTP - 跟随 301 重定向的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的用户提交 url(到 mixcloud.com 上的 mixes),我的应用使用它们来执行网络请求.

My users submit urls (to mixes on mixcloud.com) and my app uses them to perform web requests.

好的网址会返回 200 状态代码:

A good url returns a 200 status code:

uri = URI.parse("http://www.mixcloud.com/ErolAlkan/hard-summer-mix/")
request = Net::HTTP.get_response(uri)(
#<Net::HTTPOK 200 OK readbody=true>

但是如果您忘记了尾部斜杠,那么我们的其他方面很好 url 将返回 301:

But if you forget the trailing slash then our otherwise good url returns a 301:

uri = "http://www.mixcloud.com/ErolAlkan/hard-summer-mix"
#<Net::HTTPMovedPermanently 301 MOVED PERMANENTLY readbody=true> 

同样的事情发生在 404 上:

The same thing happens with 404's:

# bad path returns a 404
"http://www.mixcloud.com/bad/path/" 
# bad path minus trailing slash returns a 301
"http://www.mixcloud.com/bad/path"

  1. 如何深入"进入 301 以查看它是否将我们带到有效资源或错误页面?
  2. 是否有一种工具可以全面概述特定域可能应用于其网址的规则?

推荐答案

如果您输入的 URL 与 Web 服务器期望的 URL 不完全相同,则 301 重定向很常见.它们发生的频率比您想象的要高得多,您只是在浏览时通常不会注意到它们,因为浏览器会自动为您完成所有这些工作.

301 redirects are fairly common if you do not type the URL exactly as the web server expects it. They happen much more frequently than you'd think, you just don't normally ever notice them while browsing because the browser does all that automatically for you.

想到了两种选择:

open-uri 自动处理重定向.所以你需要做的就是:

open-uri handles redirects automatically. So all you'd need to do is:

require 'open-uri' 
...
response = open('http://xyz...').read

如果您在 HTTP 和 HTTPS 之间重定向时遇到问题,请查看这里的解决方案:
禁止 Ruby open-uri 重定向

If you have trouble redirecting between HTTP and HTTPS, then have a look here for a solution:
Ruby open-uri redirect forbidden

def get_response_with_redirect(uri)
   r = Net::HTTP.get_response(uri)
   if r.code == "301"
     r = Net::HTTP.get_response(URI.parse(r['location']))
   end
   r
end

如果您想变得更聪明,可以尝试在收到 404 响应时在 URL 中添加或删除缺少的反斜杠.您可以通过创建一个像 get_response_smart 这样的方法来实现这一点,该方法除了重定向之外还处理这个 URL 摆弄.

If you want to be even smarter you could try to add or remove missing backslashes to the URL when you get a 404 response. You could do that by creating a method like get_response_smart which handles this URL fiddling in addition to the redirects.

这篇关于Ruby Net::HTTP - 跟随 301 重定向的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆