11
function LikesDislikes () {

    $.ajax({
        url: 'http://gdata.youtube.com/feeds/api/videos/keDZXXDxK1c/ratings',
        type:"POST",
        data: '<?xml version="1.0" encoding="UTF-8"?>
            <entry xmlns="http://www.w3.org/2005/Atom"
                   xmlns:yt="http://gdata.youtube.com/schemas/2007">
                <yt:rating value="like"/>
            </entry>',
        headers: {
            "Content-Type":"application/atom+xml",
            "Content-Length":,
            "Authorization":"Bearer ya29.AHES6ZQ59RrQgujZmIjssBdYlwwLVrpCodnirdLROi7-g7U",
            "X-GData-Key":"key=AIzaSyAPrtP2Tq4m5WVInCvCWptVAKPhQ4SQNZA",
            "GData-Version":"2"
        },
        // Content-Type:"application/atom+xml",
        error: function() { alert("No data found."); },
        // contentType: "text/xml",
        success: function (response) {
            alert('response:' + response);
        }
   });

}

如何计算Content-Length上面代码中的?

4

2 回答 2

9

正如规格中所说

Content-Length entity-header字段表示entity-body的大小,以OCTET的十进制数表示

请看这个问题String length in bytes in JavaScript

基本上,如果您的数据仅包含 ASCII 字符,那么一切都应该很容易

function LikesDislikes () {

    var data = '<?xml version="1.0" encoding="UTF-8"?>
    <entry xmlns="http://www.w3.org/2005/Atom"
           xmlns:yt="http://gdata.youtube.com/schemas/2007">
        <yt:rating value="like"/>
    </entry>';

    $.ajax({
        url: 'http://gdata.youtube.com/feeds/api/videos/keDZXXDxK1c/ratings',
        type:"POST",
        data: data,
        headers: {
            "Content-Type":"application/atom+xml",
            "Content-Length": data.length,
            "Authorization":"Bearer ya29.AHES6ZQ59RrQgujZmIjssBdYlwwLVrpCodnirdLROi7-g7U",
            "X-GData-Key":"key=AIzaSyAPrtP2Tq4m5WVInCvCWptVAKPhQ4SQNZA",
            "GData-Version":"2"
        },
        // Content-Type:"application/atom+xml",
        error: function() { alert("No data found."); },
        // contentType: "text/xml",
        success: function (response) {
            alert('response:' + response);
        }
    });
}
于 2013-07-20T14:34:22.737 回答
1

Content-Length实体标头指示发送给接收者的实体主体的大小(以字节为单位)。

句法

Content-Length: <length>

指令

<length>
The length in decimal number of octets.

内容长度计算

  • 如果请求正文是字符串,您可以简单地使用正文的长度。
  • 如果请求正文是 JSON,您可以对正文进行字符串化。

const requestBody =
{
  data: 
  {
     ...
  }
};
xhr.setRequestHeader("Content-Length", JSON.stringify(requestBody).length.toString());

阅读更多: https ://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Length

于 2018-05-24T09:26:14.450 回答