8
require 'net/http'

require 'rubygems'

require 'json'

url = URI.parse('http://www.xyxx/abc/pqr')

resp = Net::HTTP.get_response(url) # get_response takes an URI object

data = resp.body

puts data

这是我在 ruby​​ 中的代码,resp.data 以 xml 形式给我数据。

rest api 默认返回 xml 数据,如果 header content-type 是 application/json 则返回 json。

但我想要 json 格式的数据。为此我必须设置 header['content-type']='application/json'。

但我不知道,如何使用 get_response 方法设置标头。获取 json 数据。

4

3 回答 3

12
def post_test
  require 'net/http'
  require 'json'
  @host = '23.23.xxx.xx'
  @port = '8080'
  @path = "/restxxx/abc/xyz"

  request = Net::HTTP::Get.new(@path, initheader = {'Content-Type' =>'application/json'})
  response = Net::HTTP.new(@host, @port).start {|http| http.request(request) }

  puts "Response #{response.code} #{response.message}: #{response.body}"
end
于 2013-04-15T08:17:52.240 回答
4

使用实例方法Net::HTTP#get修改 GET 请求的标头。

require 'net/http'

url = URI.parse('http://www.xyxx/abc/pqr')
http = Net::HTTP.new url.host
resp = http.get("#{url.path}?#{url.query.to_s}", {'Content-Type' => 'application/json'})
data = resp.body
puts data
于 2013-04-15T06:48:39.863 回答
3

你可以简单地这样做:

uri = URI.parse('http://www.xyxx/abc/pqr')
req = Net::HTTP::Get.new(uri.path, 'Content-Type' => 'application/json')

res = Net::HTTP.new(uri.host, uri.port).request(req)
于 2016-01-04T09:36:27.470 回答