2013-04-15 10 views
5
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 

questo è il mio codice in ruby, risp.data mi sta dando dati in formato xml.come impostare header ['content-type'] = 'application/json' in ruby ​​

rest api restituisce dati xml per impostazione predefinita e json se intestazione content-type è application/json.

ma voglio i dati in forma json. Per questo devo impostare header ['content-type'] = 'application/json'.

ma non so, come impostare l'intestazione con il metodo get_response. Per ottenere dati json.

+0

grazie per l'editing, e renderlo più chiaro. @rubylovely – unknownbits

risposta

10
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 
4

Utilizzare il metodo di istanza Net::HTTP#get per modificare l'intestazione di una richiesta 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 
+0

ottenendo questo errore C: \ Ruby193> test1.rb C: /Ruby193/test1.rb: 4: errore di sintassi, imprevisto ':', in attesa di tASSOC .... query.to_s} ", {' Content-Type ':' application/json '}) ...^ C: /Ruby193/test1.rb: 4: errore di sintassi, imprevisto'} ', in attesa di $ end ... tent-Type': ' application/json '}) ...^ – unknownbits

+0

@oecprashant Spiacente, questo è l'errore di hash della sintassi durante la digitazione del codice. Ho aggiornato la risposta. –

+0

ora funziona. grazie @arie shaw – unknownbits

1

Si può semplicemente fare questo:

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) 
+0

Ho fatto questo errore sull'ultima riga : NoMethodError - metodo non definito '[] 'per # : –