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

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

问题描述

我正在使用 Ruby on Rails 3,并且正在尝试实现 API 以从 Web 服务检索帐户信息.也就是说,我想连接到具有 Account 类的 Web 服务,并从在 URI http://<site_name>/accounts/1 处路由的 show 操作中获取信息.

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

现在我需要一些关于连接到网络服务的建议.在客户端应用程序中,我应该有一个 HTTP GET 请求,但我的问题是:连接到发出 HTTP 请求的 Web 服务的最佳"方法是什么?

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?

客户端应用程序中的此代码有效:

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"]

但是,上面的代码是实现 API 的方式"吗?

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

是否建议使用第三方插件和 gems?

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

推荐答案

是的,因为您正在使用 RESTful 路由,它们是您的基本 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.

还有其他实现网络服务 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.

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

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