在 Http Header 中使用 Json 字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9779860/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 18:14:14  来源:igfitidea点击:

Using Json string in the Http Header

jsonhttp-headers

提问by Win Myo Htet

Recently I run into some weird issue with http header usage ( Adding multiple custom http request headers mystery) To avoid the problem at that time, I have put the fields into json string and add that json string into header instead of adding those fields into separate http headers.

最近我遇到了一些关于 http 标头使用的奇怪问题(添加多个自定义 http 请求标头之谜)为了避免当时的问题,我将字段放入 json 字符串并将该 json 字符串添加到标头中,而不是将这些字段添加到单独的http 标头。

For example, instead of

例如,代替

request.addHeader("UserName", mUserName);
request.addHeader("AuthToken", mAuthorizationToken);
request.addHeader("clientId","android_client");

I have created a json string and add it to the single header

我创建了一个 json 字符串并将其添加到单个标题中

String jsonStr="{\"UserName\":\"myname\",\"AuthToken\":\"123456\",\"clientId\":\"android_client\"}";
request.addHeader("JSonStr",jsonStr);

Since I am new to writing Rest and dealing with the Http stuff, I don't know if my usage is proper or not. I would appreciate some insight into this.

由于我是写Rest和处理Http东西的新手,我不知道我的用法是否正确。我希望对此有所了解。

Some links

一些链接

http://lists.w3.org/Archives/Public/ietf-http-wg/2011OctDec/0133.html

http://lists.w3.org/Archives/Public/ietf-http-wg/2011OctDec/0133.html

采纳答案by Win Myo Htet

From what I understand using a json string in the header option is not as much of an abuse of usage as using http DELETE for http GET, thus there has even been proposal to use json in http header. Of course more thorough insights are still welcome and the accepted answer is still to be given.

据我了解,在 header 选项中使用 json 字符串并不像对 http GET 使用 http DELETE 那样滥用用法,因此甚至有人提议在 http 标头中使用 json。当然,仍然欢迎更深入的见解,并且仍需给出公认的答案。

回答by jchook

Yes, you may use JSON in HTTP headers, given some limitations.

是的,鉴于一些限制,您可以在 HTTP 标头中使用 JSON。

According to the HTTP spec, you MUST ensure that your header field-bodycontains only visible ASCII characters, tab, or space, and must not contain CR or LF characters (i.e. new lines, except via obsolete "folding whitespace").

根据HTTP 规范,您必须确保您的标头字段主体仅包含可见的 ASCII 字符、制表符或空格,并且不得包含 CR 或 LF 字符(即换行符,除非通过过时的“折叠空格”)。

Since many JSON encoders (e.g. json_encodein PHP) will encode both CR and LF characters as "\r" and "\n", and encode invisible or non-ASCII characters (e.g. "é" becomes "\u00e9"), you often don't need to worry about this.

由于许多 JSON 编码器(例如json_encode在 PHP 中)会将 CR 和 LF 字符编码为“\r”和“\n”,并编码不可见或非 ASCII 字符(例如,“é”变为“\u00e9”),因此您经常不不用担心这个。

Check the docs for your particular encoder or test it, though, because JSON stringstechnically allow most any UTF-8 character. For example, JSON.stringify()does not escape multibyte UTF-8, by default. However, you can easily modify it to do so, e.g.

不过,请检查特定编码器的文档或对其进行测试,因为JSON 字符串在技术上允许大多数 UTF-8 字符。例如,JSON.stringify()默认情况下不转义多字节 UTF-8。但是,您可以轻松地对其进行修改,例如

var charsToEncode = /[\u007f-\uffff]/g;
function http_header_safe_json(v) {
  return JSON.stringify(v).replace(charsToEncode,
    function(c) {
      return '\u'+('000'+c.charCodeAt(0).toString(16)).slice(-4);
    }
  );
}

Source

来源



Worth noting, the original ARPA spec (RFC 822) has a special description of this exact use case, and the spirit of this echoes in later specs such as RFC 7230:

值得注意的是,最初的 ARPA 规范(RFC 822)对这个确切的用例有一个特殊的描述,这种精神在后来的规范中得到了呼应,比如 RFC 7230:

Certain field-bodies of headers may be interpreted according to an internal syntax that some systems may wish to parse.

可以根据某些系统可能希望解析的内部语法来解释报头的某些字段主体。

Also, RFC 822 and RFC 7230 explicitly give no length constraints:

此外,RFC 822 和 RFC 7230 明确给出没有长度限制:

HTTP does not place a predefined limit on the length of each header field or on the length of the header section as a whole, as described in Section 2.5.

如第 2.5 节所述,HTTP 不会对每个标头字段的长度或整个标头部分的长度设置预定义的限制。

回答by rocketspacer

Base64encodeit before sending. Just like how JSON Web Tokendo it.
Here's a NodeJs Example:

发送前对其进行Base64 编码。就像JSON Web Token 的做法一样。
这是一个 NodeJs 示例:

var myJsonStr = JSON.stringify(myData);
var headerFriendlyStr = Buffer.from(myJsonStr, 'utf8').toString('base64');
res.addHeader('foo', headerFriendlyStr);

Decode it when you need reading:

需要阅读时解码:

var myBase64Str = req.headers['foo'];
var myJsonStr = Buffer.from(myBase64Str, 'base64').toString('utf8');
var myData = JSON.parse(myJsonStr);

回答by Kevin Junghans

Generally speaking you do not send data in the header for a REST API. If you need to send a lot of data it best to use an HTTP POST and send the data in the body of the request. But it looks like you are trying to pass credentials in the header, which some REST API's do use. Here is an example for passing the credentials in a REST API for a service called SMSIfied, which allows you to send SMS text message via the Internet. This example is using basic authentication, which is a a common technique for REST API's. But you will need to use SSL with this technique to make it secure. Here is an exampleon how to implement basic authentication with WCF and REST.

一般来说,您不会在 REST API 的标头中发送数据。如果您需要发送大量数据,最好使用 HTTP POST 并在请求正文中发送数据。但看起来您正在尝试在标头中传递凭据,某些 REST API 确实使用了这些凭据。下面是在 REST API 中为名为 SMSIfied 的服务传递凭据示例,该服务允许您通过 Internet 发送 SMS 文本消息。此示例使用基本身份验证,这是 REST API 的常用技术。但是您需要通过这种技术使用 SSL 以确保其安全。下面是一个关于如何使用 WCF 和 REST 实现基本身份验证的示例