我正在嘗試計算 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 格式,內容長度必須正確計算。任何幫助表示贊賞,謝謝。
uj5u.com熱心網友回復:
你不需要制作一個整數串列......
String bodyStr = "...";
byte[] bytes = bodyStr.getBytes(Charset.forName("UTF-8"));
int len = bytes.length;
response.setContentLength(len);
response.getOutputStream().write(bytes);
此示例使用來自 HttpServlet 的 HttpServletResponse 物件。不確定這是否是您所需要的。
我已經大量使用了它,效果很好。
uj5u.com熱心網友回復:
我自己封裝的。一般來說,我不需要計算它。除非是特殊場合。推薦okhttp3
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/312526.html
