1

我正在尝试用 ruby​​ 发出这个POST 请求。但回来 #<Net::HTTPUnsupportedMediaType:0x007f94d396bb98>我尝试的是:

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"
                            })
4

1 回答 1

4

试试这个:

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

这是API 文档和对 Net::HTTP 的简短介绍

Content-Typeand是标头,因此Accept您需要将它们作为标头发送,而不是在正文中。JSON 内容应该在请求正文中,但您需要将 Hash 转换为 JSON,而不是将其作为名称/值对中的表单数据发送。

于 2012-12-07T11:01:52.507 回答