在Ruby中HTTP Post(范例)
凉爽拍拍
・2 分钟阅读
有时候我需要在Ruby脚本中制作简单的HTTP post,使用第三方库可能对于这样一个简单的脚本来说太笨拙了。
这个文章有很多帮助,但是,它并没有覆盖我的所有需求,具体地说,在使用 Switchvox API时,API方法应该是一个JSON参数。
让我们从post一些JSON开始。
Post一些 JSON
require 'net/http'
require 'uri'
require 'json'
uri = URI.parse("http://localhost:3000/users")
header = {'Content-Type': 'text/json'}
user = {user: {
name: 'Bob',
email: 'bob@example.com'
}
}
# Create the HTTP objects
http = Net::HTTP.new(uri.host, uri.port)
request = Net::HTTP::Post.new(uri.request_uri, header)
request.body = user.to_json
# Send the request
response = http.request(request)
这将简单地提交一个POST请求。
但是,有些方法需要使用JSON提交文件?当你这样做时事情变得更加复杂了,但是,它仍然是可管理的。
用SON Post文件
require 'net/http'
require 'uri'
require 'json'
require 'mime/types'
uri = URI.parse("http://localhost:3000/users")
BOUNDARY = "AaB03x"
header = {"Content-Type": "multipart/form-data, boundary=#{BOUNDARY}"}
user = {user: {
name: 'Bob',
email: 'bob@example.com'
}
}
file = "test_file.xml"
# We're going to compile all the parts of the body into an array, then join them into one single string
# This method reads the given file into memory all at once, thus it might not work well for large files
post_body = []
# Add the file Data
post_body