簡體   English   中英

如何在ruby中設置header ['content-type'] ='application / json'

[英]how to set header['content-type']='application/json' in ruby

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數據。

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

使用實例方法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

你可以這樣做:

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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM