0

我是 Ruby on rails 的新手。我想执行 HTTP GET 和 HTTP POST 请求。对于 HTTP GET,我已经编码并且工作正常,但对于 HTTP POST,我无法弄清楚

以下是 http GET 的代码片段:

require "net/http"
require "uri"

uri = URI.parse("http://www.adobe.com")

http = Net::HTTP.new(uri.host, uri.port)
request = Net::HTTP::Get.new(uri.request_uri)
response = http.request(request)
puts response.body
4

1 回答 1

0

我使用了以下一个,您可以使用它来获取和发布。

def invoke_webservice url
query_string = url[:query_string].blank? ? "" : url[:query_string].map{ |key, value|
                 "#{key}=#{CGI.escape(value)}" }.join("&").insert(0, "?")
url[:class] = url[:class].blank? ? "" : url[:class]
webservice_uri = URI.join(APP_CONFIG['webservice_uri_format'], '/application/',
                   url[:class], url[:action], query_string)
uri = URI.parse(webservice_uri.to_s)
http = Net::HTTP.new(uri.host, uri.port)
#http.use_ssl = true
#http.verify_mode =  OpenSSL::SSL::VERIFY_NONE
http.open_timeout = 25
http.read_timeout = 500
http.start do |http|
  if url[:method] == 'get'
    request = Net::HTTP::Get.new(uri.request_uri)
  else
    request = Net::HTTP::Post.new uri.path, initheader = { 'Content-Type' => 'application/json' }
    request.body = url[:data].to_json
  end
  request.basic_auth APP_CONFIG['username'], APP_CONFIG['password']
  response = http.request request
  JSON.parse(response.body) if response.code =~ /^2\d\d$/
end
  rescue => e
puts "Error Message is #{e.inspect} #{e.backtrace}"
  end  
end
于 2013-07-03T11:08:02.250 回答