Bri*_*tul 0 json ruby-on-rails-3
我使用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
Run Code Online (Sandbox Code Playgroud)
我通过ActiveResource模型在App 2上收到它,如下所示:
class Promotion < ActiveResource::Base
self.site = "app_1_url"
self.element_name = "promotion"
end
Run Code Online (Sandbox Code Playgroud)
当我想将数据作为JSON读取时,执行以下操作,我得到406 Not Acceptable错误消息:
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
Run Code Online (Sandbox Code Playgroud)
但是,当我尝试将信息解析为XML(与上面显示的代码相同时,除了将"json"改为"xml"之外)它的工作原理.
有任何想法吗?
谢谢.
您必须将格式更改为接收数据的应用程序的JSON(App 2)
class Promotion < ActiveResource::Base
#your code
self.format = :json #XML is default
end
Run Code Online (Sandbox Code Playgroud)
这就是我如何解决这个问题(对于任何最终在这里结束的googlers)
每个维基百科:
406不可接受
请求的资源只能根据请求中发送的Accept标头生成不可接受的内容.
(基本上,您收到的数据与您想要的语言不同)
因为400级错误代码是客户端错误代码,所以我确定错误必须是App 2(在这种情况下,app 2是从app 1请求数据的客户端).我看到你在应用程序1中为JSON做了一些格式化,并在应用程序2中查找了类似的代码并且没有看到它,所以我认为错误是App 2具有与App 1不同的Content-Type标题. -Type基本上告诉应用程序/浏览器在发送/接收数据时每个语言的语言.您在Content-Type中存储的值是MIME类型,并且有很多.
你说XML类型工作但JSON没有,所以我检查了rails ActiveResource API(在App 2中使用),寻找一些头文件或内容类型方法,并看到一个format方法和属性与你在Action Controller中使用的相匹配对于App 1.我还看到,format如果没有提供,则默认为XML.
#Returns the current format, default is ActiveResource::Formats::XmlFormat.
def format
read_inheritable_attribute(:format) || ActiveResource::Formats[:xml]
end
Run Code Online (Sandbox Code Playgroud)
将此行添加到app 2中的类:
self.format = :json
Run Code Online (Sandbox Code Playgroud)
我确定您也可以使用headers方法调整Content-Type标头,但API没有示例代码显示如何执行此操作.使用headers方法调整Content-Type只是一种"更难"的方法,因为调整Content-Type是format为了简化流程而创建的常见rails .我看到API有一个调整类的format属性的例子,它方便地使用json并读取format方法/属性"设置format从mime类型引用中发送和接收的属性"也设置了Content-Type HTTP头.
| 归档时间: |
|
| 查看次数: |
2663 次 |
| 最近记录: |