0x90
0x90

Reputation: 41002

Why doesn't my http POST request go well?

I am trying to make this POST request in ruby. but get back #<Net::HTTPUnsupportedMediaType:0x007f94d396bb98> what I tried is:

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)

Tried to write this part:

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

like that:

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

this try didn't help either:

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

Upvotes: 2

Views: 768

Answers (1)

Matt
Matt

Reputation: 5398

Try this:

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

Here's the API doc and a short introduction to Net::HTTP

The Content-Type and Accept are headers, so you need to send them as headers, not in body. The JSON content should go in request body, but you need to convert your Hash to JSON and not send it as form data in name/value pairs.

Upvotes: 5

Related Questions