2012-12-07 24 views
1

我正在嘗試使這個紅寶石POST request。但回來 #<Net::HTTPUnsupportedMediaType:0x007f94d396bb98>我的嘗試是:爲什麼我的http POST請求不好?

require 'rubygems' 
require 'net/http' 
require 'uri' 
require 'json' 

auto_index_nodes =URI('http://localhost:7474/db/data/index/node/') 

request_nodes = Net::HTTP::Post.new(auto_index_nodes.request_uri) 
http = Net::HTTP.new(auto_index_nodes.host, auto_index_nodes.port) 

request_nodes.add_field("Accept", "application/json") 

request_nodes.set_form_data({"name"=>"node_auto_index", 
          "config" => { 
          "type" => "fulltext", 
          "provider" =>"lucene"} , 
          "Content-Type" => "application/json" 
          }) 


response = http.request(request_nodes) 

試圖寫入這一部分:

"config" => { 
      "type" => "fulltext", 
      provider" =>"lucene"} , 
      "Content-Type" => "application/json" 
      } 

這樣的:

"config" => '{ 
       "type" => "fulltext",\ 
       "provider" =>"lucene"},\ 
       "Content-Type" => "application/json"\ 
       }' 

這種嘗試並沒有幫助:

request_nodes.set_form_data({"name"=>"node_auto_index", 
          "config" => '{ \ 
          "type" : "fulltext",\ 
          "provider" : "lucene"}' , 
          "Content-Type" => "application/json" 
          }) 
+0

我想這是與你的服務器在這裏的響應有關,你可以調試什麼服務器響應? – Dfr

回答

3

試試這個:

require 'rubygems' 
require "net/http" 
require "uri" 
require "json" 

uri = URI.parse("http://localhost:7474/db/data/index/node/") 

req = Net::HTTP::Post.new(uri.request_uri) 
req['Content-Type'] = 'application/json' 
req['Accept'] = 'application/json' 

req.body = { 
    "name" => "node_auto_index", 
    "config" => { "type" => "fulltext", "provider" => "lucene" }, 
}.to_json  

res = Net::HTTP.start(uri.hostname, uri.port) do |http| 
    http.request(req) 
end 

這裏是the API doc and a short introduction to Net::HTTP

Content-TypeAccept是頭,所以你需要把它們發送的報頭,而不是身體。 JSON內容應該放在請求正文中,但是您需要將您的哈希轉換爲JSON,而不是將其作爲名稱/值對中的表單數據發送。