<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>

                合規國際互聯網加速 OSASE為企業客戶提供高速穩定SD-WAN國際加速解決方案。 廣告
                # Ruby `HTTPClient`教程 > 原文: [https://zetcode.com/web/rubyhttpclient/](https://zetcode.com/web/rubyhttpclient/) 在本教程中,我們展示了如何使用 Ruby `HTTPClient`模塊。 我們獲取數據,發布數據,使用 cookie 并連接到安全的網頁。 ZetCode 也有一個簡潔的 [Ruby 教程](/lang/rubytutorial/)。 超文本傳輸??協議(HTTP)是用于分布式協作超媒體信息系統的應用協議。 HTTP 是萬維網數據通信的基礎。 Ruby `HTTPClient`提供了用于通過 HTTP 訪問 Web 資源的方法。 它提供了 Ruby 中的`libwww-perl`(LWP)的功能。 (有關 Perl LWP 的信息,請參見 ZetCode 的[文章](/articles/perllwp/)。)該寶石是由中村博史創建的。 ```ruby $ sudo gem install httpclient ``` 該模塊通過`sudo gem install httpclient`命令安裝。 ```ruby $ service nginx status * nginx is running ``` 我們在本地主機上運行 nginx Web 服務器。 我們的一些示例將連接到本地運行的 nginx 服務器上的 PHP 腳本。 ## 版本 第一個程序輸出庫和 Ruby 語言的版本。 `version.rb` ```ruby #!/usr/bin/ruby require 'httpclient' puts HTTPClient::LIB_NAME puts HTTPClient::RUBY_VERSION_STRING puts HTTPClient::VERSION ``` 這三個常數提供了庫和 Ruby 版本號。 ```ruby $ ./version.rb (2.8.0, ruby 1.9.3 (2013-11-22)) ruby 1.9.3 (2013-11-22) 2.8.0 ``` 這是示例的示例輸出。 ## ·get_content·函數 `get_content`是一種用于獲取由給定 URL 標識的文檔的高級方法。 `get_content.rb` ```ruby #!/usr/bin/ruby require 'httpclient' client = HTTPClient.new cont = client.get_content 'http://www.something.com' puts cont ``` 該腳本獲取`www.something.com`網頁的內容。 ```ruby cont = client.get_content 'http://www.something.com' ``` `get_content`方法將結果作為一個字符串返回。 ```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 'httpclient' client = HTTPClient.new client.get_content('http://www.something.com') do |chunk| puts chunk.gsub(%r{</?[^>]+?>}, '') end ``` 該腳本會剝離`www.something.com`網頁的 HTML 標簽。 ```ruby client.get_content('http://www.something.com') do |chunk| puts chunk.gsub(%r{</?[^>]+?>}, '') end ``` 一個簡單的正則表達式用于剝離 HTML 標記。 在這種情況下,`get_content`方法以字符串塊的形式返回內容。 ```ruby $ ./strip_tags.rb Something. Something. ``` 該腳本將打印網頁的標題和內容。 ## 請求 HTTP 請求是從客戶端發送到瀏覽器的消息,以檢索某些信息或采取某些措施。 `HTTPClient`的`request`方法創建一個新請求。 請注意,`HTTPClient`類具有諸如`get`,`post`或`put`之類的方法,這些方法為我們節省了一些輸入。 `create_request.rb` ```ruby #!/usr/bin/ruby require 'httpclient' client = HTTPClient.new method = 'GET' url = URI.parse 'http://www.something.com' res = client.request method, url puts res.body ``` 該示例創建一個 GET 請求并將其發送到`http://www.something.com`。 ```ruby method = 'GET' url = URI.parse 'http://www.something.com' ``` 我們創建一個請求方法和 URL。 ```ruby res = client.request method, url ``` 使用`request`方法發出請求。 ```ruby puts res.body ``` 消息響應的`body`屬性包含消息的正文。 ```ruby $ ./create_request.rb <html><head><title>Something.</title></head> <body>Something.</body> </html> ``` 這是示例的輸出。 ## 狀態 `HTTP::Message`表示 HTTP 請求或響應。 其`status`方法返回響應的 HTTP 狀態代碼。 `status.rb` ```ruby #!/usr/bin/ruby require 'httpclient' client = HTTPClient.new res = client.get 'http://www.something.com' puts res.status puts HTTP::Status::successful? res.status res = client.get 'http://www.something.com/news/' puts res.status puts HTTP::Status::successful? res.status res = client.get 'http://www.urbandicionary.com/define.php?term=Dog' puts res.status puts HTTP::Status::successful? res.status ``` 我們使用`get`方法執行三個 HTTP 請求,并檢查返回的狀態。 ```ruby puts HTTP::Status::successful? res.status ``` `HTTP::Status::successful?`方法指示狀態代碼是否成功。 ```ruby $ ./status.rb 200 true 404 false 302 false ``` 200 是對成功的 HTTP 請求的標準響應,404 指示找不到請求的資源,302 指示該資源已臨時重定向。 ## `head`方法 `head`方法檢索文檔標題。 標頭由字段組成,包括日期,服務器,內容類型或上次修改時間。 `head.rb` ```ruby #!/usr/bin/ruby require 'httpclient' client = HTTPClient.new res = client.head 'http://www.something.com' puts "Server: " + res.header['Server'][0] puts "Last modified: " + res.header['Last-Modified'][0] puts "Content type: " + res.header['Content-Type'][0] puts "Content length: " + res.header['Content-Length'][0] ``` 該示例打印服務器,`www.something.com`網頁的上次修改時間,內容類型和內容長度。 ```ruby $ ./head.rb Server: Apache/2.4.12 (FreeBSD) OpenSSL/1.0.1l-freebsd mod_fastcgi/mod_fastcgi-SNAP-0910052141 Last modified: Mon, 25 Oct 1999 15:36:02 GMT Content type: text/html Content length: 77 ``` 這是`head.rb`程序的輸出。 ## `get`方法 `get`方法向服務器發出 GET 請求。 GET 方法請求指定資源的表示形式。 `greet.php` ```ruby <?php echo "Hello " . htmlspecialchars($_GET['name']); ?> ``` 在`/usr/share/nginx/html/`目錄中,有此`greet.php`文件。 該腳本返回`name`變量的值,該值是從客戶端檢索到的。 `htmlspecialchars()`函數將特殊字符轉換為 HTML 實體; 例如`&amp;`。 `mget.rb` ```ruby #!/usr/bin/ruby require 'httpclient' client = HTTPClient.new res = client.get 'http://localhost/greet.php?name=Jan' puts res.body ``` 該腳本將帶有值的變量發送到服務器上的 PHP 腳本。 該變量直接在 URL 中指定。 ```ruby $ ./mget.rb Hello Jan ``` This is the output of the example. ```ruby $ tail -1 /var/log/nginx/access.log 127.0.0.1 - - [08/May/2016:13:15:31 +0200] "GET /greet.php?name=Jan HTTP/1.1" 200 19 "-" "HTTPClient/1.0 (2.8.0, ruby 1.9.3 (2013-11-22))" ``` 我們檢查了 nginx 訪問日志。 `get`方法采用第二個參數,我們可以在其中指定查詢參數。 `mget2.rb` ```ruby #!/usr/bin/ruby require 'httpclient' client = HTTPClient.new query = {'name' => 'Jan'} res = client.get 'http://localhost/greet.php', query puts res.body ``` 該示例與上一個示例基本相同。 ```ruby $ ./mget2.rb Hello Jan ``` This is the output of the example. ## 重定向 重定向是將一個 URL 轉發到另一個 URL 的過程。 HTTP 響應狀態代碼 301“永久移動”用于永久 URL 重定向。 ```ruby location = /oldpage.html { return 301 /files/newpage.html; } ``` 將這些行添加到位于 Debian 上`/etc/nginx/sites-available/default`的 Nginx 配置文件中。 ```ruby $ sudo service nginx restart ``` 編輯完文件后,我們必須重新啟動 nginx 才能應用更改。 `newpage.html` ```ruby <!DOCTYPE html> <html> <head> <title>New page</title> </head> <body> <p> This is a new page </p> </body> </html> ``` 這是位于 nginx 文檔根目錄中的`newpage.html`文件。 `redirect.rb` ```ruby #!/usr/bin/ruby require 'httpclient' client = HTTPClient.new res = client.get 'http://localhost/oldpage.html', :follow_redirect => true puts res.body ``` 該腳本訪問舊頁面并遵循重定向。 ```ruby res = client.get 'http://localhost/oldpage.html', :follow_redirect => true ``` `:follow_redirect`選項用于遵循重定向。 ```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 $ tail -2 /var/log/nginx/access.log 127.0.0.1 - - [09/May/2016:14:08:50 +0200] "GET /oldpage.html HTTP/1.1" 301 193 "-" "HTTPClient/1.0 (2.8.0, ruby 1.9.3 (2013-11-22))" 127.0.0.1 - - [09/May/2016:14:08:50 +0200] "GET /files/newpage.html HTTP/1.1" 200 113 "-" "HTTPClient/1.0 (2.8.0, ruby 1.9.3 (2013-11-22))" ``` 從`access.log`文件中可以看到,該請求已重定向到新的文件名。 通信包含兩個 GET 消息。 ## 用戶代理 在本節中,我們指定用戶代理的名稱。 `agent.php` ```ruby <?php echo $_SERVER['HTTP_USER_AGENT']; ?> ``` 在 nginx 文檔根目錄中,我們有這個簡單的 PHP 文件。 它返回用戶代理的名稱。 `agent.rb` ```ruby #!/usr/bin/ruby require 'httpclient' client = HTTPClient.new default_header: {"User-Agent" => "Ruby script"} res = client.get 'http://localhost/agent.php' puts res.body ``` 該腳本為`agent.php`腳本創建一個簡單的 GET 請求。 ```ruby client = HTTPClient.new default_header: {"User-Agent" => "Ruby script"} ``` 在`HTTPClient`的構造器中,我們指定用戶代理。 ```ruby $ ./agent.rb Ruby script ``` 服務器使用我們隨請求發送的代理名稱進行了響應。 ## `post`方法 `post`方法在給定的 URL 上調度 POST 請求,為填寫的表單內容提供鍵/值對。 `target.php` ```ruby <?php echo "Hello " . htmlspecialchars($_POST['name']); ?> ``` 在本地 Web 服務器上,我們有此`target.php`文件。 它只是將過帳的值打印回客戶。 `post_value.rb` ```ruby #!/usr/bin/ruby require 'httpclient' client = HTTPClient.new query = {"name" => "Jan"} res = client.post 'http://localhost/target.php', query puts res.body ``` 腳本使用具有`Jan`值的`name`鍵發送請求。 POST 請求通過`post`方法發出。 ```ruby $ ./mpost.rb Hello Jan ``` 這是`mpost.rb`腳本的輸出。 ```ruby $ tail -1 /var/log/nginx/access.log 127.0.0.1 - - [08/May/2016:13:38:57 +0200] "POST /target.php HTTP/1.1" 200 19 "-" "HTTPClient/1.0 (2.8.0, ruby 1.9.3 (2013-11-22))" ``` 使用 POST 方法時,不會在請求 URL 中發送該值。 ## 從字典中檢索定義 在以下示例中,我們在 [www.dictionary.com](http://www.dictionary.com) 上找到術語的定義。 要解析 HTML,我們使用`nokogiri`。 可以使用`sudo gem install nokogiri`命令安裝。 `get_term.rb` ```ruby #!/usr/bin/ruby require 'httpclient' require 'nokogiri' client = HTTPClient.new term = 'dog' res = client.get 'http://www.dictionary.com/browse/'+term doc = Nokogiri::HTML res.body doc.css("div.def-content").map do |node| puts node.text.strip!.gsub(/\s{3,}/, " ") end ``` 在此腳本中,我們在`www.dictionary.com`上找到了術語狗的定義。 `Nokogiri::HTML`用于解析 HTML 代碼。 ```ruby res = client.get 'http://www.dictionary.com/browse/'+term ``` 為了執行搜索,我們在 URL 的末尾附加了該詞。 ```ruby doc = Nokogiri::HTML res.body doc.css("div.def-content").map do |node| puts node.text.strip!.gsub(/\s{3,}/, " ") end ``` 我們使用`Nokogiri::HTML`類解析內容。 定義位于`<div class="def-content">`標簽內。 我們通過刪除過多的空白來改善格式。 ## cookie HTTP cookie 是從網站發送并在用戶瀏覽時存儲在用戶的 Web 瀏覽器或程序數據子文件夾中的一小段數據。 當用戶訪問網頁時,瀏覽器/程序會將 cookie 發送回服務器,以通知用戶先前的活動。 Cookies 的有效期限為有效期。 接收到 HTTP 請求時,服務器可以發送帶有響應的`Set-Cookie`標頭。 之后,cookie 值將以 Cookie HTTP 標頭的形式與對同一服務器的所有請求一起發送。 `cookies.php` ```ruby <?php $theme = $_COOKIE['theme']; if (isset($theme)) { echo "Your theme is $theme"; } else { echo "You are using default theme"; setcookie('theme', 'black-and-white', time() + (86400 * 7)); } ?> ``` 該 PHP 文件讀取 cookie。 如果 cookie 不存在,則會創建它。 cookie 存儲用戶的主題。 `send_cookie.rb` ```ruby #!/usr/bin/ruby require 'httpclient' url = URI.parse "http://localhost/cookies.php" cookie = WebAgent::Cookie.new cookie.name = "theme" cookie.value = "green-and-black" cookie.url = url client = HTTPClient.new client.cookie_manager.add cookie res = client.get url puts res.body ``` 我們創建一個自定義 cookie,并將其發送到`cookies.php`頁面。 ```ruby cookie = WebAgent::Cookie.new cookie.name = "theme" cookie.value = "green-and-black" cookie.url = url ``` 使用`WebAgent::Cookie`類創建一個 cookie。 ```ruby client = HTTPClient.new client.cookie_manager.add cookie ``` cookie 被添加到 cookie 管理器中。 ```ruby $ ./send_cookie.rb Your theme is green-and-black ``` This is the output of the example. 接下來,我們將讀取 cookie 并將其本地存儲在文件中。 `read_cookie.rb` ```ruby #!/usr/bin/ruby require 'httpclient' client = HTTPClient.new res = client.get 'http://localhost/cookies.php' client.set_cookie_store 'cookie.dat' p res.header["Set-Cookie"] client.save_cookie_store ``` 該腳本從 PHP 文件讀取 cookie,并將其本地存儲在`cookie.dat`文件中。 最后,我們讀取存儲的 cookie,并將其發送到同一 PHP 文件。 `send_cookie2.rb` ```ruby #!/usr/bin/ruby require 'httpclient' client = HTTPClient.new cm = HTTPClient::CookieManager.new 'cookie.dat' cm.load_cookies client.cookie_manager = cm res = client.get 'http://localhost/cookies.php' p res.body ``` `HTTPClient::CookieManager`用于讀取 cookie。 ```ruby $ ./send_cookie.rb Unknown key: Max-Age = 604800 "You are using default theme" $ ./read_cookie.rb Unknown key: Max-Age = 604800 ["theme=black-and-white; expires=Sun, 15-May-2016 16:00:08 GMT; Max-Age=604800"] $ ./send_cookie.rb "Your theme is black-and-white" ``` 我們運行腳本。 作者認為,警告消息[應忽略](https://github.com/nahi/httpclient/issues/242)。 ## 證書 客戶端的`set_auth`方法設置用于領域的名稱和密碼。 安全領域是一種用于保護 Web 應用資源的機制。 ```ruby $ sudo apt-get install apache2-utils $ sudo htpasswd -c /etc/nginx/.htpasswd user7 New password: Re-type new password: Adding password for user user7 ``` 我們使用`htpasswd`工具創建用于基本 HTTP 認證的用戶名和密碼。 ```ruby location /secure { auth_basic "Restricted Area"; auth_basic_user_file /etc/nginx/.htpasswd; } ``` 在 nginx `/etc/nginx/sites-available/default`配置文件中,我們創建一個安全頁面。 領域的名稱是`"Restricted Area"`。 `index.html` ```ruby <!DOCTYPE html> <html lang="en"> <head> <title>Secure page</title> </head> <body> <p> This is a secure page. </p> </body> </html> ``` 在`/usr/share/nginx/html/secure`目錄中,我們有這個 HTML 文件。 `credentials.rb` ```ruby #!/usr/bin/ruby require 'httpclient' user = 'user7' passwd = '7user' client = HTTPClient.new client.set_auth 'http://localhost/secure/', user, passwd cont = client.get_content 'http://localhost/secure/' puts cont ``` 該腳本連接到安全網頁; 它提供訪問該頁面所需的用戶名和密碼。 ```ruby $ ./credentials.rb <!DOCTYPE html> <html lang="en"> <head> <title>Secure page</title> </head> <body> <p> This is a secure page. </p> </body> </html> ``` 使用正確的憑據,`credentials.rb`腳本返回受保護的頁面。 在本教程中,我們使用了 Ruby `HTTPClient`模塊。 在 ZetCode 上有類似的 [Ruby Faraday 教程](/web/rubyfaraday/)和 [Ruby `Net::HTTP`教程](/web/rubynethttp/)。
                  <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>

                              哎呀哎呀视频在线观看