温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

Ruby在Linux中处理网络请求重定向

发布时间:2024-09-15 19:26:31 来源:亿速云 阅读:82 作者:小樊 栏目:建站服务器

在 Linux 系统中,使用 Ruby 处理网络请求重定向的方法有很多

  1. 使用 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
  1. 使用 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 处理网络请求重定向。你可以根据自己的需求和喜好选择其中一种方法。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI