require 'net/http'
require 'uri'
# 1. 解析URL
uri = URI('https://example.com/api')
# 2. 创建HTTP对象
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true if uri.scheme == 'https'
# 3. 构建表单数据
form_data = {
key1: 'value1',
key2: 'value2'
}.to_query
# 4. 创建POST请求对象
request = Net::HTTP::Post.new(uri.request_uri, 'Content-Type' => 'application/x-www-form-urlencoded')
request.body = form_data
# 5. 发送请求并获取响应
response = http.request(request)
puts response.body
- 解析URL:使用
URI
类解析目标URL,以便后续获取主机、端口等信息。
- 创建HTTP对象:根据解析出的主机和端口创建
Net::HTTP
对象,若URL是https
协议则开启SSL。
- 构建表单数据:将表单数据以哈希形式存储,通过
to_query
方法转换为符合application/x-www-form-urlencoded
格式的字符串。
- 创建POST请求对象:创建
Net::HTTP::Post
请求对象,设置请求头Content-Type
为application/x-www-form-urlencoded
,并将表单数据放入请求体。
- 发送请求并获取响应:使用HTTP对象发送请求并获得响应,
response.body
可获取响应内容。