https://github.com/rest-client/rest-clienthttps://github.com/jnunemaker/httparty
http://ruby-doc.org/stdlib-2.1.2/libdoc/net/http/rdoc/Net/HTTP.html https://www.imququ.com/post/four-ways-to-post-data-in-http.html
工作中常用到获取一个xml或者json格式的数据进行解析,获取我们希望拿到的有效数据,这时候用的是http的get请求,当我们提交表单和上传文件的时候,用的是http的post请求,post请求的contentType分两种,提交普通的表单的时候,Content-Type是"application/x-www-form-urlencoded",上传文件的时候,Content-Type是"multipart/form-data"这个可以通过浏览器的调试工具查看点击F12打开页面调试工具,然后选择"Network"->"Headers"->"Request Headers"->"Content-Type" 接下来我们分别看一下应用的场景 (一)REST Client获取xml/json数据 (1)xmlresponse = RestClient.get(url)
url_hash = Hash.from_xml(response.body) (2)json
response = RestClient.get(url_list[index])
url_hash = JSON.parse(response.body)[‘headline_videos‘]
(二)httpparty获取json数据
response = HTTParty.get(‘https://api.stackexchange.com/2.2/questions?site=stackoverflow‘)
============================== RestClient最大的优势在于在post请求的时候能够上传一个文件,
module ClassMethods def upload_image(file_path) timestamp = Time.now.to_i response = RestClient.post Settings.upload.image.url, { uid: Settings.upload.image.uid, appkey: Settings.upload.image.appkey, timestamp: timestamp, sign: sign(timestamp), filename: "ott_cms_#{timestamp}", duplmd5: Settings.upload.image.duplmd5, file: File.new(file_path) } case response.code when 200 parse_upload_response response else { errors: ["图片上传服务暂时不可用"] } end end
REST Client – simple DSL for accessing HTTP and REST resources
时间: 2024-11-15 00:40:46