0

I am trying to use net::http to do a post request.

My request using net:http fails with following error:

respnose_body,code: ["{\"message\":\"Validation Failed\",\"errors\":{\"direction\":[\"invalid\"]}}",
   "422"]]

My request works fine using curl on teminal:

curl https://$$.com/$$ \
>     -u usr:Pssd! \
>     -X POST \
>     -H 'Accept: application/json' \
>     -H 'Content-Type: application/json' \
>     -d '{"body":"my body"}'

However the same request , I try to execute using nett:http as

 http_headers => {"Accept" => "application/json", "Content-Type" => "application/json"}

 uri=URI.parse(url)
      http = Net::HTTP.new(uri.host, uri.port)
      http.use_ssl = true
      http.verify_mode = OpenSSL::SSL::VERIFY_NONE
      request = Net::HTTP::Post.new(uri.request_uri)
      http_headers.each{|key,value| request.add_field(key,value)}
      request.body = form_data  
      response=http.request(request)

The form_data is passed as a json using hash.to_json . 

Now the same NET:HTTP code works for a different post request (on a different uri) executed exactly the same.

The service expects data to be sent and received as json.

Any suggestions to debug this .

Thanks!

Update: Added the way I am setting up headers

codeObserver
  • 6,521
  • 16
  • 76
  • 121
  • How are you setting equivalent header to the curl `-H 'Content-Type: application/json'` in your net::http code? I can't see it . . . I'd expect to see a `request.header` or similar (going to check correct syntax . . . ) – Neil Slater Apr 04 '13 at 19:10

1 Answers1

1

Try:

request = Net::HTTP::Post.new(uri.request_uri, {'Content-Type' =>'application/json'})

or:

request = Net::HTTP::Post.new(uri.request_uri)
request["Content-Type"] = "application/json"
Neil Slater
  • 26,512
  • 6
  • 76
  • 94
  • Thanks Neil. I added the way I set headers. Basically I do request.add_field(key,value) and it worked for other post requests I am making. My hunch is its in the data that I am passing but I am not sure (validation failed might mean json data validation ?) – codeObserver Apr 04 '13 at 20:50
  • Also tried request[key]=value instead of using request.add_field . It still fails with the same error – codeObserver Apr 04 '13 at 21:18