Ruby程序中发送基于HTTP协议的请求的简单示例
1.建立HTTP连接(通过GET方式发送请求参数)
require"open-uri" #如果有GET请求参数直接写在URI地址中 uri='http://uri' html_response=nil open(uri)do|http| html_response=http.read end putshtml_response require"open-uri" #如果有GET请求参数直接写在URI地址中 uri='http://uri' html_response=nil open(uri)do|http| html_response=http.read end putshtml_response
2.通过POST发送请求参数
params={} params["name"]='Tom' uri=URI.parse("http://uri") res=Net::HTTP.post_form (uri,params) #返回的cookie putsres.header['set-cookie'] #返回的htmlbody putsres.body params={} params["name"]='Tom' uri=URI.parse("http://uri") res=Net::HTTP.post_form (uri,params) #返回的cookie putsres.header['set-cookie'] #返回的htmlbody putsres.body
3.HTTPS请求
# #描述: #发送快递数据到datasystem,使用https #输入: #data-组装后的expess的数据 #输出: #datasystem返回的状态信息 # defself.senddatassl(url,data) url=url+data $logger.info(url) begin uri=URI.parse(URI.escape(url)) http=Net::HTTP.new(uri.host,uri.port) http.use_ssl=true if($logger!=nil) $logger.info("链接地址参数:#{URI.escape(url)},文件名:#{__FILE__},第#{__LINE__}行") $logger.info("传入data参数:#{data.to_json},文件名:#{__FILE__},第#{__LINE__}行") end request=Net::HTTP::Get.new(uri.request_uri) response=http.request(request) rescue=>exception $logger.error("传递url地址为#{url},错误!#{exception.to_s},文件名:#{__FILE__},第#{__LINE__}行") returnnil end returnresponse.body end