当前位置:首页 > Web开发 > 正文

net/http使用代办代理

2024-03-31 Web开发

标签:

环境配置:

确认环境。

ruby -v

环境搭建好之后,直接引入内置模块使用即可。

代码样例

使用代办代理

# -*- coding: utf-8 -*- require 'net/http' # 引入内置net/http模块 require 'zlib' require 'stringio' # 代办代理处事器ip 和 端口 proxy_ip = '47.115.5.19' proxy_port = 16816 # 要访谒的方针网页, 以快代办代理testproxy页面为例 page_url = "https://dev.kuaidaili.com/testproxy" uri = URI(page_url) # 新建代办代理实例 proxy = Net::HTTP::Proxy(proxy_ip, proxy_port) # 创建新的请求东西 req = Net::HTTP::Get.new(uri) # 设置User-Agent req['User-Agent'] = 'Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_6_8; en-us) AppleWebKit/534.50 (KHTML, like Gecko) Version/5.1 Safari/534.50' req['Accept-Encoding'] = 'gzip' # 使用gzip压缩传输数据让访谒更快 # 使用代办代理倡议请求, 若访谒的是http网页, 请将use_ssl设为false res = proxy.start(uri.hostname, uri.port, :use_ssl => true) do |http| http.request(req) end # 输出状态码 puts "status code: #{res.code}" # 输出响应体 if res.code.to_i != 200 then puts "page content: #{res.body}" else gz = Zlib::GzipReader.new(StringIO.new(res.body.to_s)) puts "page content: #{gz.read}" end

运行下尝尝,看当作果。告成,code200,

技术图片

进阶学习:

Ruby——net/http使用代办代理

标签:

原文地点:https://www.cnblogs.com/kuaidaili/p/12305443.html

温馨提示: 本文由Jm博客推荐,转载请保留链接: https://www.jmwww.net/file/web/30160.html