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
?
答案 0 :(得分:6)
Content-Length实体标题字段指示的大小 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);
}
});
}
答案 1 :(得分:0)
Content-Length 实体标头指示发送给收件人的实体主体的大小(以字节为单位)。
Content-Length: <length>
<length>
The length in decimal number of octets.
const requestBody =
{
data:
{
...
}
};
xhr.setRequestHeader("Content-Length", JSON.stringify(requestBody).length.toString());
了解详情: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Length