我使用ActiveResource构建了一个Rails应用程序,该应用程序由另一个应用程序调用(Rails也是如此)。
情况是,我将第一个应用程序的信息公开为JSON,如下所示:
应用1:
class PromotionsController < ApplicationController
# GET /promotions
# GET /promotions.xml
def index
@promotions = Promotion.all
respond_to do |format|
format.json { render :json => @promotions }
end
end
end我在应用程序2上通过ActiveResource模型接收它,如下所示:
class Promotion < ActiveResource::Base
self.site = "app_1_url"
self.element_name = "promotion"
end当我想以JSON格式读取数据时,执行以下操作,我得到406不可接受的错误消息:
class PromotionsController < ApplicationController
# GET /promotions
# GET /promotions.xml
def index
@promotions = Promotion.all
respond_to do |format|
format.json { render :json => @promotions }
end
end
end但是,当我尝试将信息解析为XML (执行与上面显示的代码相同的操作,只是将"json“改为"xml”)时,它可以正常工作。
有什么想法吗?
谢谢。
发布于 2012-04-13 22:36:06
您必须将接收数据的应用程序的格式更改为JSON (应用程序2)
class Promotion < ActiveResource::Base
#your code
self.format = :json #XML is default
end以下是我是如何弄清楚这一点的(对于任何在这里结束的谷歌人来说)
步骤1:研究错误代码
406不可接受的
被请求的资源只能根据请求中发送的Accept头部生成不可接受的内容。
(基本上,您收到的数据使用的语言与您需要的语言不同)
步骤2:诊断问题
因为400级错误代码是客户端错误代码,所以我确定错误一定是与应用程序2有关(在本例中,应用程序2是从应用程序1请求数据的客户端)。我看到你在app 1中为JSON做一些格式化,并且在App 2中寻找类似的代码,但是没有看到它,所以我假设错误是由于App 2具有与App 1不同的头。您在Content-Type中存储的值是,并且有很多这样的值。
您说XML类型可以工作,但JSON不行,所以我检查了rails (在应用程序2中使用),查找一些头或内容类型方法,发现了一个format方法和属性,它与您在应用程序1的Action Controller中使用的方法和属性相匹配。我还看到,如果没有提供,format将默认为XML。
#Returns the current format, default is ActiveResource::Formats::XmlFormat.
def format
read_inheritable_attribute(:format) || ActiveResource::Formats[:xml]
end第3步:修复thangz
将下面这一行添加到应用程序2的类中:
self.format = :json我确信您也可以使用headers方法调整Content-Type头,但API没有显示如何执行此操作的示例代码。使用headers方法调整Content-Type是一种比较“困难”的方式,而且因为调整Content-Type非常常见,所以rails创建了format来简化流程。我看到该应用程序接口有an example of adjusting the format attribute of the class that conveniently uses json,并且读到format方法/属性“设置从mime类型引用发送和接收属性的format”,也就是设置Content-Type HTTP头。
https://stackoverflow.com/questions/10131686
复制相似问题