在 Linux 系统中,使用 Ruby 处理网络请求重定向的方法有很多
net/http
标准库:require 'net/http'
require 'uri'
def fetch(uri_str, limit = 10)
raise ArgumentError, 'too many HTTP redirects' if limit == 0
uri = URI(uri_str)
response = Net::HTTP.get_response(uri)
case response
when Net::HTTPSuccess then
response
when Net::HTTPRedirection then
location = response['location']
fetch(location, limit - 1)
else
response.value
end
end
url = 'http://example.com'
response = fetch(url)
puts response.body
httparty
gem:首先,安装 httparty gem:
gem install httparty
然后,使用以下代码处理重定向:
require 'httparty'
def fetch(url, limit = 10)
raise ArgumentError, 'too many HTTP redirects' if limit == 0
response = HTTParty.get(url, follow_redirects: false)
case response.code
when 200
response
when 301, 302
location = response.headers['Location']
fetch(location, limit - 1)
else
raise "Unexpected response code: #{response.code}"
end
end
url = 'http://example.com'
response = fetch(url)
puts response.body
这两种方法都可以在 Linux 系统中使用 Ruby 处理网络请求重定向。你可以根据自己的需求和喜好选择其中一种方法。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。