简体   繁体   English

将JSON数据作为发布方法从Rails控制器发送到Web服务

[英]Send JSON data as post method from rails controller to a web service

I am trying to send some json data from my controller written in rails to a java webservice. 我正在尝试将我的控制器中用Rails编写的一些json数据发送到Java Web服务。

On form submission i take all the input fields data do some procession on it and convert it into json object using to_json. 在表单提交时,我将所有输入字段数据都进行一些处理,然后使用to_json将其转换为json对象。

But how can i send it to java webservice 但是如何将其发送到Java WebService

http://localhost:8080/exim/jsonToMapService?jsonData={"key":"value"}

You can use net/http . 您可以使用net/http (as @Pierre wrote, you should create a class in lib folder, and put there your function) (如@Pierre所写,您应该在lib文件夹中创建一个类,并在其中放置您的函数)

url = URI.parse(service_url)
headers = {"host" => URL }
req = Net::HTTP::Post.new(url.path)
req["Content-Type"] = "application/json"
req["Accept"] = "application/json"

req.body = JSON.generate(some_data)

con = Net::HTTP.new(url.host, url.port)

# ssl for https
if full_url.include?("https")
  con.use_ssl = true
  con.verify_mode = OpenSSL::SSL::VERIFY_NONE
end

res = con.start {|http| http.request(req) }

To do things like this I suggest using either RestClient or Faraday . 为此,我建议使用RestClientFaraday Howeve I strongly suggest not doing the HTTP call in your controller. 但是,我强烈建议不要在控制器中进行HTTP调用。

Using RestClient, it would look like this: 使用RestClient,它看起来像这样:

RestClient.get('http://localhost:8080/exim/jsonToMapService', { key: :value })

You should create a class to extract this logic in the lib folder for example. 例如,您应该创建一个类来提取此逻辑在lib文件夹中。

As @eightbitraptor mentioned it, when performing HTTP request like above, you should avoid blocking by performing them in a background process like Delayed Job , Resque or Sideqik . 就像@eightbitraptor提到的那样,在执行上述HTTP请求时,应避免在诸如Delayed JobResqueSideqik的后台进程中执行它们来避免阻塞。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM