![](/img/trans.png)
[英]What value should I use for Content-Length of an POST HTTP request?
[英]How to calculate Content-Length of a request body of a Http Post Request
我正在尝试计算 http 发布请求的请求正文的内容长度,但我不断收到指示错误内容长度的错误。 请求正文如下所示:
Map<String, String> body = {
'grant_type': 'authorization_code',
'client_id': 'clientid',
'code': authCode,
'redirect_uri': 'http://localhost:8080/login/callback',
'code_verifier':
'codeverifier',
};
我尝试了几种解决方案,例如将正文的内容连接成一个字符串,例如以下内容,然后将其转换为字节数组并发送它的长度,但没有奏效。
String bodyStr = "grant_type:authorization_code" +
"client_id:clientid" +
"code:{$authCode}" +
"redirect_uri:http://localhost:8080/login/callback" +
"code_verifier:codeverifier";
List<int> bytes = utf8.encode(bodyStr);
post 请求正文是 x-www-form-urlencoded 格式,内容长度必须正确计算。 任何帮助表示赞赏,谢谢。
你不需要制作一个整数列表......
String bodyStr = "...";
byte[] bytes = bodyStr.getBytes(Charset.forName("UTF-8"));
int len = bytes.length;
response.setContentLength(len);
response.getOutputStream().write(bytes);
此示例使用来自 HttpServlet 的 HttpServletResponse 对象。 不确定这是否是您所需要的。
我已经大量使用了它,效果很好。
我自己封装的。 一般来说,我不需要计算它。 除非是特殊场合。 推荐okhttp3
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.