首页 > 解决方案 > 无法在 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());
        }
    }

标签: javadiscord

解决方案


通过使用 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);
    }
}

推荐阅读