【发布时间】:2021-11-16 22:45:46
【问题描述】:
我正在尝试向 Discord 发送 POST 请求,但我无法授权我的机器人,并且每次运行命令时都会收到 403 响应代码。我的令牌没有错,因为我可以使用 CURL 创建一个 POST 请求并获得正确的响应
@Override
public void doCommand(CommandEvent event) throws IOException {
String jsonInputString = "{\"max_age\": 86400, \"max_uses\": 0, \"target_application_id\":880218394199220334, \"target_type\":2, \"temporary\": false, \"validate\": null}";
String botToken = "*token*";
String current = event.getMember().getVoiceState().getChannel().getId();
URL url = new URL ("https://discord.com/api/v8/channels/" + current + "/invites");
HttpURLConnection con = (HttpURLConnection)url.openConnection();
con.setRequestMethod("POST");
con.setRequestProperty("Authorization", "Bot " + botToken);
con.setRequestProperty("Content-Type", "application/json; utf-8");
con.setRequestProperty("Accept", "application/json");
con.setDoOutput(true);
try(OutputStream os = con.getOutputStream()) {
byte[] input = jsonInputString.getBytes(StandardCharsets.UTF_8);
os.write(input, 0, input.length);
}
try(BufferedReader br = new BufferedReader(
new InputStreamReader(con.getInputStream(), StandardCharsets.UTF_8))) {
StringBuilder response = new StringBuilder();
String responseLine = null;
while ((responseLine = br.readLine()) != null) {
response.append(responseLine.trim());
}
event.reply(response.toString());
}
}
【问题讨论】:
-
response.append(responseLine.trim()).append("\r\n"); -
byte[] input = (jsonInputString + "\r\n").getB...可能还有os.flush() -
试过了,没用
-
我强烈推荐使用合适的 http 客户端。由于您似乎在使用 JDA,因此您可以使用
event.getJDA().getHttpClient()来获取库使用的 OkHttp 客户端。 -
我试试,谢谢