Posting JSON params from java to sinatra service

ⅰ亾dé卋堺 提交于 2019-12-02 07:39:21
goyalankit

It turns out that the problem is with the way Sinatra gets its params. I was able to solve my problem using Kyle's awesome response to this post: Sinatra controller params method coming in empty on JSON post request

Code:

before do
  if request.request_method == "POST" and request.content_type=="application/json"
    body_parameters = request.body.read
    parsed = body_parameters && body_parameters.length >= 2 ? JSON.parse(body_parameters) : nil
    params.merge!(parsed)
  end
end

Alternate Method: However, I found a better solution to deal with it, by adding a middleware to do the same for me. I used rack-contrib gem. Following are the changes I did in my code:

EDIT:

use git to get the version where issue related to content type application/json;charset=UTF-8 is fixed

Gemfile:

gem 'rack-contrib', git: 'git@github.com:rack/rack-contrib', ref: 'b7237381e412852435d87100a37add67b2cfbb63'

config.ru:

use Rack::PostBodyContentTypeParser

source: http://jaywiggins.com/2010/03/using-rack-middleware-to-parse-json/

Using the following worked much better for me. I had to add request.body.rewind and :symbolize_names => true (while calling JSON.parse)

before do
  if request.request_method == "POST" and (request.content_type || '').include? "application/json" 
    request.body.rewind
    body_parameters = request.body.read
    parsed = body_parameters && body_parameters.length >= 2 ? JSON.parse(body_parameters, :symbolize_names => true) : nil
    params.merge!(parsed)
  end
end
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!