<ruby id="bdb3f"></ruby>

    <p id="bdb3f"><cite id="bdb3f"></cite></p>

      <p id="bdb3f"><cite id="bdb3f"><th id="bdb3f"></th></cite></p><p id="bdb3f"></p>
        <p id="bdb3f"><cite id="bdb3f"></cite></p>

          <pre id="bdb3f"></pre>
          <pre id="bdb3f"><del id="bdb3f"><thead id="bdb3f"></thead></del></pre>

          <ruby id="bdb3f"><mark id="bdb3f"></mark></ruby><ruby id="bdb3f"></ruby>
          <pre id="bdb3f"><pre id="bdb3f"><mark id="bdb3f"></mark></pre></pre><output id="bdb3f"></output><p id="bdb3f"></p><p id="bdb3f"></p>

          <pre id="bdb3f"><del id="bdb3f"><progress id="bdb3f"></progress></del></pre>

                <ruby id="bdb3f"></ruby>

                ??一站式輕松地調用各大LLM模型接口,支持GPT4、智譜、豆包、星火、月之暗面及文生圖、文生視頻 廣告
                # Ruby `Net::HTTP`教程 > 原文: [https://zetcode.com/web/rubynethttp/](https://zetcode.com/web/rubynethttp/) 在本教程中,我們展示了如何使用標準的 Ruby `Net::HTTP`模塊。 我們獲取數據,發布數據,使用 JSON 并連接到安全的網頁。 本教程使用 Sinatra 應用作為幾個示例。 Zetcode 也有一個簡潔的 [Ruby 教程](/lang/rubytutorial/)。 超文本傳輸??協議(HTTP)是用于分布式協作超媒體信息系統的應用協議。 HTTP 是萬維網數據通信的基礎。 Ruby `Net::HTTP`提供了一個豐富的庫,可用于構建 HTTP 客戶端。 ## Sinatra Sinatra 是流行的 Ruby Web 應用框架。 它易于安裝和設置。 我們的一些示例還將使用 Sinatra 應用。 ```ruby $ sudo gem install sinatra $ sudo gem install thin ``` 我們安裝 Sinatra 和 Thin Web 服務器。 如果安裝了 Thin,Sinatra 會自動選擇默認 WEBrick 服務器上的 Thin。 ```ruby $ pwd /home/janbodnar/prog/sinatra/first $ ls main.rb ``` 在第一個目錄中,我們有一個`main.rb`文件,它是 Sinatra 應用文件。 `main.rb` ```ruby require 'sinatra' get '/' do "First application" end ``` 應用對`/`路由做出反應。 它將一條簡單的消息發送回客戶端。 ```ruby $ ruby main.rb == Sinatra (v1.4.7) has taken the stage on 4567 for development with backup from Thin Thin web server (v1.6.4 codename Gob Bluth) Maximum connections set to 1024 Listening on localhost:4567, CTRL+C to stop ``` 使用`ruby main.rb`命令啟動應用。 瘦服務器啟動; 它在 4567 端口上監聽。 ```ruby $ curl localhost:4567/ First application ``` 使用`curl`命令行工具,我們連接到服務器并訪問`/`路由。 一條消息出現在控制臺上。 ## 版本 第一個程序確定庫的版本。 `version.rb` ```ruby #!/usr/bin/ruby require 'net/http' puts Net::HTTP::version_1_1? puts Net::HTTP::version_1_2? ``` 該腳本確定`net/http`是處于 1.1 版還是 1.2 版模式。 ```ruby $ ./version.rb false true ``` 在我們的情況下,模式為 1.2。 ## 獲取內容 `get_print`是一種高級方法,可從目標獲取正文并將其輸出到標準輸出。 `get_content.rb` ```ruby #!/usr/bin/ruby require 'net/http' uri = URI 'http://www.something.com/' Net::HTTP.get_print uri ``` 該腳本獲取`www.something.com`網頁的內容。 `net/http`設計為與`uri`模塊緊密配合。 ```ruby require 'net/http' ``` 這也需要`uri`,因此我們不需要單獨要求它。 ```ruby $ ./get_content.rb <html><head><title>Something.</title></head> <body>Something.</body> </html> ``` 這是`get_content.rb`腳本的輸出。 以下程序獲取一個小型網頁,并剝離其 HTML 標簽。 `strip_tags.rb` ```ruby #!/usr/bin/ruby require 'net/http' uri = URI "http://www.something.com/" doc = Net::HTTP.get uri puts doc.gsub %r{</?[^>]+?>}, '' ``` 該腳本會剝離`www.something.com`網頁的 HTML 標簽。 ```ruby puts doc.gsub %r{</?[^>]+?>}, '' ``` 一個簡單的正則表達式用于剝離 HTML 標記。 ```ruby $ ./strip_tags.rb Something. Something. ``` 該腳本將打印網頁的標題和內容。 ## 狀態 響應的`code`和`message`方法給出其狀態。 `status.rb` ```ruby #!/usr/bin/ruby require 'net/http' uri = URI 'http://www.something.com' res = Net::HTTP.get_response uri puts res.message puts res.code uri = URI 'http://www.something.com/news/' res = Net::HTTP.get_response uri puts res.message puts res.code uri = URI 'http://www.urbandicionary.com/define.php?term=Dog' res = Net::HTTP.get_response uri puts res.message puts res.code ``` 我們使用`get_response`方法執行三個 HTTP 請求,并檢查返回的狀態。 ```ruby uri = URI 'http://www.something.com/news/' res = Net::HTTP.get_response uri puts res.message puts res.code ``` 使用`message`和`code`方法檢查 HTTP 響應的狀態。 ```ruby $ ./status.rb OK 200 Not Found 404 Found 302 ``` 200 是對成功的 HTTP 請求的標準響應,404 指示找不到請求的資源,302 指示該資源已臨時重定向。 ## `head`方法 `head`方法檢索文檔標題。 標頭由字段組成,包括日期,服務器,內容類型或上次修改時間。 `head.rb` ```ruby #!/usr/bin/ruby require 'net/http' uri = URI "http://www.something.com" http = Net::HTTP.new uri.host, uri.port res = http.head '/' puts res['server'] puts res['date'] puts res['last-modified'] puts res['content-type'] puts res['content-length'] ``` 該示例打印`www.something.com`網頁的服務器,日期,上次修改時間,內容類型和內容長度。 ```ruby $ ./head.rb Apache/2.4.12 (FreeBSD) OpenSSL/1.0.1l-freebsd mod_fastcgi/mod_fastcgi-SNAP-0910052141 Wed, 11 May 2016 19:30:56 GMT Mon, 25 Oct 1999 15:36:02 GMT text/html 77 ``` 這是`head.rb`程序的輸出。 ## `get`方法 `get`方法向服務器發出 GET 請求。 GET 方法請求指定資源的表示形式。 `main.rb` ```ruby require 'sinatra' get '/greet' do "Hello #{params[:name]}" end ``` 這是 Sinatra 應用文件。 收到`/greet`路由后,它將返回一條消息,其中包含客戶端發送的名稱。 `mget.rb` ```ruby #!/usr/bin/ruby require 'net/http' uri = URI "http://localhost:4567/greet" params = { :name => 'Peter' } uri.query = URI.encode_www_form params puts Net::HTTP.get uri ``` 該腳本將具有值的變量發送到 Sinatra 應用。 該變量直接在 URL 中指定。 ```ruby params = { :name => 'Peter' } ``` 這是我們發送到服務器的參數。 ```ruby uri.query = URI.encode_www_form params ``` 我們使用`encode_www_form`方法將參數編碼到 URL 中。 ```ruby puts Net::HTTP.get uri ``` `get`方法將 GET 請求發送到服務器。 它返回打印到控制臺的響應。 ```ruby $ ./mget.rb Hello Peter ``` 這是示例的輸出。 ```ruby 127.0.0.1 - - [11/May/2016:21:51:12 +0200] "GET /greet?name=Peter HTTP/1.1" 200 11 0.0280 ``` 在瘦服務器的此日志中,我們可以看到參數已編碼到 URL 中。 我們可以直接將參數放入 URL 字符串中。 `mget2.rb` ```ruby #!/usr/bin/ruby require 'net/http' uri = URI "http://localhost:4567/greet?name=Peter" puts Net::HTTP.get uri ``` 這是發出 GET 消息的另一種方式。 它基本上與前面的示例相同。 ```ruby $ ./mget2.rb Hello Peter ``` This is the output of the example. ## 用戶代理 在本節中,我們指定用戶代理的名稱。 `main.rb` ```ruby require 'sinatra' get '/agent' do request.user_agent end ``` Sinatra 應用返回客戶端發送的用戶代理。 `agent.rb` ```ruby #!/usr/bin/ruby require 'net/http' uri = URI "http://localhost:4567" http = Net::HTTP.new uri.host, uri.port res = http.get '/agent', {'User-Agent' => 'Ruby script'} puts res.body ``` 該腳本向 Sinatra 應用創建一個簡單的 GET 請求。 ```ruby res = http.get '/agent', {'User-Agent' => 'Ruby script'} ``` 用戶代理在`get`方法的第二個參數中指定。 ```ruby $ ./agent.rb Ruby script ``` 服務器使用我們隨請求發送的代理名稱進行了響應。 ## `post`方法 `post`方法在給定的 URL 上調度 POST 請求,為填寫的表單內容提供鍵/值對。 `main.rb` ```ruby require 'sinatra' post '/target' do "Hello #{params[:name]}" end ``` Sinatra 應用在`/target`路由上返回問候語。 它從`params`哈希中獲取值。 `mpost.rb` ```ruby #!/usr/bin/ruby require 'net/http' uri = URI "http://localhost:4567/target" params = { :name => 'Peter' } res = Net::HTTP.post_form uri, params puts res.body ``` 腳本使用具有`Peter`值的`name`鍵發送請求。 POST 請求通過`Net::HTTP.post_form`方法發出。 ```ruby $ ./mpost.rb Hello Peter ``` 這是`mpost.rb`腳本的輸出。 ```ruby 127.0.0.1 - - [12/May/2016:11:36:16 +0200] "POST /target HTTP/1.1" 200 11 0.0006 ``` 使用 POST 方法時,不會在請求 URL 中發送該值。 ## 從字典中檢索定義 在以下示例中,我們在 [www.dictionary.com](http://www.dictionary.com) 上找到術語的定義。 要解析 HTML,我們使用`nokogiri`包。 可以使用`sudo gem install nokogiri`命令安裝。 `get_term.rb` ```ruby #!/usr/bin/ruby require 'net/http' require 'nokogiri' term = 'cat' uri = URI 'http://www.dictionary.com/browse/'+term res = Net::HTTP.get uri doc = Nokogiri::HTML res doc.css("div.def-content").map do |node| s = node.text.strip! s.gsub!(/\s{3,}/, " ") unless (s == nil) puts s unless (s == nil) end ``` 在此腳本中,我們在`www.dictionary.com`上找到了術語`cat`的定義。 `Nokogiri::HTML`用于解析 HTML 代碼。 ```ruby uri = URI 'http://www.dictionary.com/browse/'+term ``` 為了執行搜索,我們在 URL 的末尾附加了該詞。 ```ruby doc = Nokogiri::HTML res doc.css("div.def-content").map do |node| s = node.text.strip! s.gsub!(/\s{3,}/, " ") unless (s == nil) puts s unless (s == nil) end ``` 我們使用`Nokogiri::HTML`類解析內容。 定義位于`<div class="def-content">`標簽內。 我們通過刪除過多的空白來改善格式。 ## JSON 格式 JSON (JavaScript 對象表示法)是一種輕量級的數據交換格式。 人類很容易讀寫,機器也很容易解析和生成。 ```ruby $ sudo gem install json ``` 如果以前沒有安裝過,則必須安裝`json`包。 `main.rb` ```ruby require 'sinatra' require 'json' get '/example.json' do content_type :json { :name => 'Jane', :age => 17 }.to_json end ``` Sinatra 應用發送 JSON 數據。 它使用`to_json`方法完成工作。 `parse_json.rb` ```ruby #!/usr/bin/ruby require 'net/http' require 'json' uri = URI 'http://localhost:4567/example.json' res = Net::HTTP.get uri data = JSON.parse res puts data["name"] puts data["age"] ``` 該示例讀取 Sinatra 應用發送的 JSON 數據。 ```ruby $ ./parse_json.rb Jane 17 ``` This is the output of the example. 接下來,我們從 Ruby 腳本將 JSON 數據發送到 Sinatra 應用。 `main.rb` ```ruby require 'sinatra' require 'json' post '/readjson' do data = JSON.parse request.body.read "#{data["name"]} is #{data["age"]} years old" end ``` 該應用讀取 JSON 數據并發送回帶有已解析值的消息。 `post_json.rb` ```ruby #!/usr/bin/ruby require 'net/http' require 'json' uri = URI 'http://localhost:4567/readjson' req = Net::HTTP::Post.new uri.path, initheader = {'Content-Type' =>'application/json'} req.body = {:name => 'Jane', :age => 17}.to_json res = Net::HTTP.start(uri.hostname, uri.port) do |http| http.request req end puts res.body ``` 該腳本將 JSON 數據發送到 Sinatra 應用并讀取其響應。 ```ruby req = Net::HTTP::Post.new uri.path, initheader = {'Content-Type' =>'application/json'} ``` `'application/json'`內容類型必須在請求的標頭中指定。 ```ruby $ ./post_json.rb Jane is 17 years old ``` This is the output of the example. ## 重定向 重定向是將一個 URL 轉發到另一個 URL 的過程。 HTTP 響應狀態代碼 302 用于臨時 URL 重定向。 `main.rb` ```ruby require 'sinatra' get "/oldpage" do redirect to("/files/newpage.html"), 302 end ``` 在 Sinatra 應用中,我們使用`redirect`命令重定向到其他位置。 `newpage.html` ```ruby <!DOCTYPE html> <html> <head> <title>New page</title> </head> <body> <p> This is a new page </p> </body> </html> ``` 這是位于`public/files`子目錄中的`newpage.html`文件。 `redirect.rb` ```ruby #!/usr/bin/ruby require 'net/http' uri = URI 'http://localhost:4567/oldpage' res = Net::HTTP.get_response uri if res.code == "302" res = Net::HTTP.get_response URI res.header['location'] end puts res.body ``` 該腳本訪問舊頁面并遵循重定向。 請注意,這適用于單個重定向。 ```ruby res = Net::HTTP.get_response URI res.header['location'] ``` 標頭的位置字段包含文件重定向到的地址。 ```ruby $ ./redirect.rb <!DOCTYPE html> <html> <head> <title>New page</title> </head> <body> <p> This is a new page </p> </body> </html> ``` This is the output of the example. ```ruby 127.0.0.1 - - [12/May/2016:12:51:24 +0200] "GET /oldpage HTTP/1.1" 302 - 0.0006 127.0.0.1 - - [12/May/2016:12:51:24 +0200] "GET /files/newpage.html HTTP/1.1" 200 113 0.0006 ``` 從日志中,我們可以看到該請求已重定向到新的文件名。 通信包含兩個 GET 消息。 ## 證書 `basic_auth`方法設置用于領域的名稱和密碼。 安全領域是一種用于保護 Web 應用資源的機制。 ```ruby $ sudo gem install sinatra-basic-auth ``` 對于此示例,我們需要安裝`sinatra-basic-auth`包。 `main.rb` ```ruby require 'sinatra' require "sinatra/basic_auth" authorize do |username, password| username == "user7" && password == "7user" end get '/' do "hello" end protect do get "/secure" do "This is restricted area" end end ``` 在 Sinatra 應用中,我們指定授權邏輯并設置受保護的路由。 `credentials.rb` ```ruby #!/usr/bin/ruby require 'net/http' uri = URI 'http://localhost:4567/secure' req = Net::HTTP::Get.new uri.path req.basic_auth 'user7', '7user' res = Net::HTTP.start uri.hostname, uri.port do |http| http.request req end puts res.body ``` 該腳本連接到安全網頁; 它提供訪問該頁面所需的用戶名和密碼。 ```ruby $ ./credentials.rb This is restricted area ``` 使用正確的憑據,`credentials.rb`腳本返回受限制的數據。 在本教程中,我們使用了 Ruby `net/http`模塊。 在 ZetCode 上也有類似的 [Ruby `HTTPClient`教程](/web/rubyhttpclient/)和 [Ruby Faraday 教程](/web/rubyfaraday/)。
                  <ruby id="bdb3f"></ruby>

                  <p id="bdb3f"><cite id="bdb3f"></cite></p>

                    <p id="bdb3f"><cite id="bdb3f"><th id="bdb3f"></th></cite></p><p id="bdb3f"></p>
                      <p id="bdb3f"><cite id="bdb3f"></cite></p>

                        <pre id="bdb3f"></pre>
                        <pre id="bdb3f"><del id="bdb3f"><thead id="bdb3f"></thead></del></pre>

                        <ruby id="bdb3f"><mark id="bdb3f"></mark></ruby><ruby id="bdb3f"></ruby>
                        <pre id="bdb3f"><pre id="bdb3f"><mark id="bdb3f"></mark></pre></pre><output id="bdb3f"></output><p id="bdb3f"></p><p id="bdb3f"></p>

                        <pre id="bdb3f"><del id="bdb3f"><progress id="bdb3f"></progress></del></pre>

                              <ruby id="bdb3f"></ruby>

                              哎呀哎呀视频在线观看