Blog

Blog

PHODAL

IoT CoAP Content Format与application/json

在做IoT-CoAP的过程中只支持JSON,查阅CoAP的草稿时发现支持了诸多的Content Types。

CoAP Content Types

以下文字来自谷歌翻译:

互联网媒体类型是通过HTTP字符串标识,如“application/xml”。该字符串是由一个顶层的类型“applicaion”和子类型的“XML”。为了尽量减少使用这些类型的媒体类型来表示的开销消息有效载荷,COAP定义一个标识符编码方案互联网媒体类型的子集。预计这桌将可扩展标识符的值的IANA维护。内容类型选项被格式化为一个8位无符号整数。初始映射到一个合适的互联网媒体类型标识符表所示。复合型高层次类型(multipart和不支持消息)。标识符值是从201-255保留的特定于供应商的,应用程序特定的或实验使用和不由IANA。

下面是HTTP的标识符及类型

Internet media type Identifier
text/plain (UTF-8) 0
text/xml (UTF-8) 1
text/csv (UTF-8) 2
text/html (UTF-8) 3
image/gif 21
image/jpeg 22
image/png 23
image/tiff 24
audio/raw 25
video/raw 26
application/link-format [I-D.ietf-core-link-format] 40
application/xml 41
application/octet-stream 42
application/rdf+xml 43
application/soap+xml 44
application/atom+xml 45
application/xmpp+xml 46
application/exi 47
application/x-bxml 48
application/fastinfoset 49
application/soap+fastinfoset 50
application/json 51

而在CoAP中只有简单地几个

Media type Encoding Id. Reference
text/plain; - 0 [RFC2046][RFC3676][RFC5147]
charset=utf-8
application/ - 40 [RFC6690]
link-format
application/xml - 41 [RFC3023]
application/ - 42 [RFC2045][RFC2046]
octet-stream
application/exi - 47 [EXIMIME]
application/json - 50 [RFC4627]

简单地说就是:

诸如application/json的Content Types在CoAP中应该是50。如上表所示的结果是其对应的结果,这样的话可以减少传递的信息量。

IoT CoAP JSON

于是在一开始的时候首先支持的便是"application/json"这样的类型。

首先判断请求的header

request_helper.getHandler = function(req, res) {
    switch (req.headers['Accept']) {
        case "application/json":
            qh.returnJSON(req, res);
            break;
        case "application/xml":
            qh.returnXML(req, res);
            break;
    }
};

再转至相应的函数处理,而判断的依据则是Accept是不是"application/json"。

registerFormat('text/plain', 0)
registerFormat('application/link-format', 40)
registerFormat('application/xml', 41)
registerFormat('application/octet-stream', 42)
registerFormat('application/exi', 47)
registerFormat('application/json', 50)

对应地我们需要在一发出请求的时候设置好Accept,要不就没有办法返回我们需要的结果。

req.setHeader("Accept", "application/json");

关于我

Github: @phodal     微博:@phodal     知乎:@phodal    

微信公众号(Phodal)

围观我的Github Idea墙, 也许,你会遇到心仪的项目

QQ技术交流群: 321689806
comment

Feeds

RSS / Atom

最近文章

关于作者

Phodal Huang

Engineer, Consultant, Writer, Designer

ThoughtWorks 技术专家

工程师 / 咨询师 / 作家 / 设计学徒

开源深度爱好者

出版有《前端架构:从入门到微前端》、《自己动手设计物联网》、《全栈应用开发:精益实践》

联系我: h@phodal.com

微信公众号: 最新技术分享

标签