自用笔记片段 ruby net/http

来源:互联网 发布:unity3d 阴影锯齿 编辑:程序博客网 时间:2024/06/01 16:41

常用类

Class

Net::HTTP::Get
Net::HTTP::Head
Net::HTTP::Post
Net::HTTP::Put

Public Class Methods

get(uri_or_host, path = nil, port = nil)print Net::HTTP.get(URI('http://www.example.com/index.html'))print Net::HTTP.get('www.example.com', '/index.html')

可以以传入uri或者host, path, port = 80
返回的是字符串

get_print(uri_or_host, path = nil, port = nil)Net::HTTP.get_print URI('http://www.example.com/index.html')Net::HTTP.get_print 'www.example.com', '/index.html'

结果会输出到界面

get_response(uri_or_host, path = nil, port = nil, &block)res = Net::HTTP.get_response(URI('http://www.example.com/index.html'))print res.bodyres = Net::HTTP.get_response('www.example.com', '/index.html')print res.body

结果返回Net::HTTPResponse 的对象,可以调用各种方法,查看属性

默认端口号:
http_default_port()
The default port to use for HTTP requests; defaults to 80.
https_default_port()
The default port to use for HTTPS requests; defaults to 443.

Net::HTTP。new(address, port = nil, p_addr = :ENV, p_port = nil, p_user = nil, p_pass = nil)
新建一个Net::HTTP对象, 可选传入proxy port user pwd
如果不传入proxy,URI::Generic#find_proxy可查看系统的proxy

Net::HTTP.new(address, port = nil)
创建连接,如用到才打开

post_form(url, params) post require 'net/http'require 'uri'Net::HTTP.post_form URI('http://www.example.com/search.cgi'),                    { "q" => "ruby", "max" => "50" }

传入的参数是hash

start(address, port, p_addr, p_port, p_user, p_pass, &block)
start(address, port=nil, p_addr=nil, p_port=nil, p_user=nil, p_pass=nil, opt, &block)
创建一个http连接带一个块,块中代码执行完毕连接即停。

version_1_2()
Public Instance Methods
active?()
continue_timeout=(sec)设置持续

Public Instance Methods

finish()
Finishes the HTTP session and closes the TCP connection. Raises IOError if the session has not been started.

get(path, initheader = {}, dest = nil) { |body_segment| … }

http1 = Net::HTTP.new(uri.host, uri.port)        request1 = Net::HTTP::Get.new(uri.request_uri)response = http.get(request1)

post(path, data, initheader = nil, dest = nil) { |body_segment| … }

response = http.post('/cgi-bin/search.rb', 'query=foo')# using blockFile.open('result.txt', 'w') {|f|  http.post('/cgi-bin/search.rb', 'query=foo') do |str|    f.write str  end}

inspect()

Net::HTTP.get(‘example.com’, ‘/index.html’) # => String 调用get

uri = URI(‘http://example.com/index.html?count=10‘) #解析String
Net::HTTP.get(uri) # => String 调用get
uri=URI(’http://www.pogo.com/games/aces‘)解析出来的是哈希
scheme: http
userinfo
host: www.pogo.com
port: 80
registry
path /games/aces
opaque
query
fragment
p uri.scheme # => “http” p uri.host # => “www.pogo.com” p uri.port # => 80 p uri.path # => “/games/aces”

p uri.request_uri # => “/games/aces”
http1 = Net::HTTP.new(uri.host, uri.port) 建立连接,不带http
request1 = Net::HTTP::Get.new(uri.request_uri) 建立请求/games/aces
建立请求后可以对请求header编辑,通过哈希传入参数
比如 request1[“User-Agent”] = ‘GoogleBot’
request1[“Accept”] = “/
===============request headers===========================
Accept text/html,application/xhtml+xml,application/xml;q=0.9,/;q=0.8
Accept-Encoding gzip, deflate
Accept-Language en-US,en;q=0.5
Connection keep-alive
Cookie com.pogo.alpha.unid=242931940197174; _ga=GA1.2.1570154562.1480317149; __gads=ID=f90995fc66ebe94f:T=1480317144:S=ALNI_MYBDXOfexlDbwPSp3yZ8qydNz8TLw; com.pogo.unid=6788715502485145; com.pogo.ofAge=1; __atuvc=7%7C48%2C5%7C49; com.pogo.alpha.ofAge=1; __utma=103122817.1570154562.1480317149.1480413416.1480485564.2; __utmz=103122817.1480485564.2.2.utmcsr=pogodev.pogo.com|utmccn=(referral)|utmcmd=referral|utmcct=/games/undiscovered-world; alpha.JID=F77C1EB2DFDF5DB0A9755AD051C02663.33; com.pogo.alpha.lkey_creation=”Mon Dec 05 08:56:36 GMT 2016”; prod.JID=D28E150C2CB4504E3F1B4A378D041802.17; com.pogo.lkey=OWJjODI4NGMtMzAwZC00NTg2LWIxN2YtZWU0MmNmODkxMWE2.161205081902; com.pogo.lkey_creation=”Mon Dec 05 08:19:02 GMT 2016”; com.pogo.alpha.coupontool.type=subs; com.pogo.alpha.coupontool.screenname=ct01
Host www.alpha.pogo.com
Upgrade-Insecure-Requests 1
User-Agent Mozilla/5.0 (Windows NT 10.0; WOW64; rv:50.0) Gecko/20100101 Firefox/50.0
=============================response==========================




require 'uri'p URI.join('http://www.pogo.com/', '/games/aces/')p URI.parse('http://www.pogo.com/')+'/games/aces/' #<URI::HTTP http://www.pogo.com/games/aces/>#<URI::HTTP http://www.pogo.com/games/aces/>

URI.decode(str) 可以解码

URI::HTTP#request_uri 返回path + ‘?’ + query。
注意 Net::HTTP.get(‘example.com’, ‘/index.html’) # => String
get 后面网址不要带http(s),它是scheme, example.com 是host, /index.html 是path
注意区别:
uri = URI(‘http://example.com/index.html?count=10‘)
Net::HTTP.get(uri) # => String

Postrequire 'uri'require 'net/http'Net::HTTP.start('www.pogo.com', 80) {|http| # start means ending when block ends  response = http.post('/misc/gamesearch/gamesearch.do',                       'pogoword=Aces+Up%21')  puts response.code}uri = URI('http://www.pogo.com/misc/gamesearch/gamesearch.do')http1 = Net::HTTP.new(uri.hostname, uri.port) # new a http link and open when necessaryreqpost = Net::HTTP::Post.new(uri)  # new a post reqpost.set_form_data('pogoword' => 'Aces+Up%21') #edit uri.queryresp = http1.request(reqpost )#post what you definedputs resp.code

注意,可以不建立http连接,直接post

require 'uri'require 'net/http'uri = URI.parse('http://www.pogo.com/misc/gamesearch/gamesearch.do')res = Net::HTTP.post_form(uri, 'pogoword' => 'Aces+Up%21')puts res.code

uri = URI(‘http://www.example.com/search.cgi‘)
res = Net::HTTP.post_form(uri, ‘q’ => ‘ruby’, ‘max’ => ‘50’)
puts res.body
注意 http 请求,传入网址不带http,post,输入path,和“请求参数”
require ‘uri’
uri= URI(“https://www.alpha.pogo.com/misc/gamesearch/gamesearch.do?pogoword=Aces+Up%21“)
puts uri.query #=》’pogoword=Aces+Up%21

require 'uri'require 'net/http'uri = URI.parse('http://www.pogo.com/misc/gamesearch/gamesearch.do')res = Net::HTTP.post_form(uri, 'pogoword' => 'Aces+Up%21')#如何处理responseputs res.codeputs res['Set-Cookie']  #this is a stringputs res.to_hash['set-cookie']  #this is an arrayputs "Headers: #{res.to_hash.inspect}" #this is header hashputs res.code       # => '200'puts res.message    # => 'OK'puts res.class.name # => 'HTTPOK'

req.basic_auth ‘user’, ‘pass’
Basic authentication is performed according to RFC2617
处理
HTTPS

HTTPS is enabled for an HTTP connection by #use_ssl=.uri = URI('https://secure.example.com/some_path?query=string')Net::HTTP.start(uri.host, uri.port,  :use_ssl => uri.scheme == 'https') do |http|  request = Net::HTTP::Get.new uri  response = http.request request # Net::HTTPResponse objectend

Proxies

proxy_addr = 'your.proxy.host'proxy_port = 8080Net::HTTP.new('example.com', nil, proxy_addr, proxy_port).start { |http|  # always proxy via your.proxy.addr:8080}
0 0
原创粉丝点击