markdown 在Ruby中进行GET请求

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了markdown 在Ruby中进行GET请求相关的知识,希望对你有一定的参考价值。

### Making Requests in Ruby
* **Using `net/http`**
  * make sure your file: `require 'net/http'`
  * this will also `require 'uri'` so you don't need to manually include this

```ruby
uri = URI('http://www.blahblah.com')
// same as uri = URI.parse('http://www.blahblah.com')

Net::HTTP.start(uri.host, uri.port) do |http|
 request = Net::HTTP.Get.new uri
 
 response = http.request request # Net::HTTPResponse object
end
```
* `.start` creates a connection to an HTTP server and keeps the connection for the duration of the block
* connection will remain open for any requests within the block as well
* `Post` requests are similar, just follow [posting request](https://docs.ruby-lang.org/en/2.0.0/Net/HTTP.html#class-Net::HTTP-label-POST)
  * `post` requests are made outside the start of the connection
* You can specify the content_type and body params for the URI:
```ruby
uri = URI("www....")
request = Net::HTTP.Post.new uri.path

// HEADER
request.content_type = "application/json"

// BODY
// dump converts the json to a string
request.body = JSON.dump({
  "arg1" => "val1",
  "arg2" => "val2", 
  ...
})
```
---
### Enable HTTPS
```ruby
uri = "www.google.com/sjf"

Net:HTTP.start(uri.hostname, uri.port, :use_ssl => uri.scheme == "https") do |http|

request = Net::HTTP.Get.new uri
resp = http.request request

end
```
---

以上是关于markdown 在Ruby中进行GET请求的主要内容,如果未能解决你的问题,请参考以下文章

Ruby 网络请求

Ruby 网络请求

Ruby on Rails 路由解析

使用 Ruby on Rails 的 HTTP GET 请求:OpenSSL::SSL::SSLError

ruby 在单独的线程中使用多个连接进行http请求的简单类

更好的 ruby​​ markdown 解释器?