java - 无法在 java 中使用 post 请求进行授权
问题描述
我正在尝试向 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());
}
}
解决方案
通过使用 OkHttp 而不是 HttpUrlConnection 来修复它
感谢乔普·埃根!
@Override
public void doCommand(CommandEvent event) throws IOException {
String current = event.getMember().getVoiceState().getChannel().getId();
URL url = new URL ("https://discord.com/api/v8/channels/" + current + "/invites");
String postBody = "{\"max_age\": \"86400\", \"max_uses\": 0, \"target_application_id\":\"880218394199220334\", \"target_type\":2, \"temporary\": false, \"validate\": null}";
RequestBody body = RequestBody.create(
MediaType.parse("application/json"), postBody);
OkHttpClient client = new OkHttpClient.Builder()
.addInterceptor(
new DefaultContentTypeInterceptor())
.build();
Request request = new Request.Builder()
.url(url)
.post(body)
.build();
Call call = client.newCall(request);
Response response = call.execute();
JSONObject obj = new JSONObject(response.body().string());
String code = obj.getString("code");
event.reply("https://discord.com/invite/" + code);
response.close();
}
UPD:我尝试使用 event.getJDA().getHttpClient(),但我无法授权不和谐。制作了我自己的客户端拦截器
public class DefaultContentTypeInterceptor implements Interceptor {
public Response intercept(Interceptor.Chain chain) throws IOException {
Config config = ConfigFactory.load();
Request originalRequest = chain.request();
Request requestWithUserAgent = originalRequest
.newBuilder()
.header("Content-Type", "application/json")
.header("Authorization", "Bot " + config.getString("token"))
.build();
return chain.proceed(requestWithUserAgent);
}
}
推荐阅读
- c# - Is there a way to add multiple variables together without implicitly declaration
- sql - 当一个表包含(id,start_date)而另一个包含(id,end_date)时,如何连接两个表以确定日期范围
- r - 根据另一个变量 r 中的值变化生成一个新变量
- flutter - 在颤动中处理未来
- javascript - 如何使用javascript对第二个数组中的属性进行分组
- python - 将多列 Python 中的匹配对组合在一起
- vb.net - 根据一个文本框值从访问数据库中自动填充文本框
- flutter - 启用后 TextFormField 未聚焦
- excel - 如何使用 VBA 从 Word 文档中提取未知数量的电子邮件地址/所有电子邮件地址
- jekyll - 为什么我必须在更改 _includes 后运行 bundle exec jekyll serve 才能看到更改?