连接Web服务使用Rails(HTTP请求)? [英] Connecting to web services using Rails (HTTP requests)?

查看:215
本文介绍了连接Web服务使用Rails(HTTP请求)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我on Rails的3使用Ruby,我想实现的API来检索Web服务帐户信息。也就是说,我想连接到具有Account类的Web服务,并从显示操作路由的URI HTTP信息:/ /<&SITE_NAME GT; /账户/ 1

I am using Ruby on Rails 3 and I am trying to implement APIs to retrieve account information from a web service. That is, I would like to connect to a web service that has the Account class and get information from the show action routed at the URI http://<site_name>/accounts/1.

在这个时候,在Web服务 accounts_controller.rb 文件我有:

At this time, in the web service accounts_controller.rb file I have:

class AccountsController < ApplicationController
  def show
    @account = Account.find(params[:id])

    respond_to do |format|
      format.html
      format.js
      format.json { render :json => @account.to_json }
    end
  end
end

现在我需要连接到Web服务的一些建议。在客户端应用程序,我应该有一个HTTP GET请求,但这里是我的问题:什么是最好的方式来连接到Web服务的HTTP请求?

Now I need some advice for connecting to the web service. In the client application, I should have a HTTP GET request, but here is my question: What is "the best" approach to connect to a web service making HTTP requests?

这code客户端应用程序的工作原理:

This code in the client application works:

url = URI.parse('http://<site_name>/accounts/1.json')
req = Net::HTTP::Get.new(url.path)
res = Net::HTTP.start(url.host, url.port) {|http|
  http.request(req)
}

@output = JSON(res.body)["account"]

不过,是上面code的方式来实现的API?

but, is the above code "the way" to implement APIs?

是不是最好使用第三​​方插件和宝石?

Is it advisable to use third-party plugins and gems?

推荐答案

是的,因为你使用的 REST风格的路线,他们是你的基本的API。你还返回结构化的JSON数据容易耗由应用程序。

Yes, since you're using RESTful routes, they are your basic API. You're also returning structured JSON data easily consumable by an application.

有其他的方法来实现Web服务API(例如: SOAP ),但是这是良好和正确的方法。

There are other ways to implement a web services API (e.g. SOAP), but this is a good and proper way.

因为它是一个Web服务API,连接到正确的URL和解析响应是去在客户端的方式。但如果你需要访问许多不同的资源可能是创建构建请求URL的一种灵活的方式是一个好主意。

Since it's a web services API, connecting to the correct URL and parsing the response is the way to go on the client side. Though if you need to access many different resources it might be a good idea to create a flexible way of building the request URL.

这篇关于连接Web服务使用Rails(HTTP请求)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆