【问题标题】:Can't authorize with post request in java无法在 java 中使用 post 请求进行授权
【发布时间】: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 客户端。
  • 我试试,谢谢

标签: java discord


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    880218394199220334

    这是高度怀疑。 JSON 规范没有说明数字会有多大,但这个数字不是有效的双精度数,它是那么大。如果您要通过在 javascript 中简单地 eval()ing 来读取这个 JSON(这是相当相关的,因为 JSON 中的 JS 代表 JavaScript),那么这个数字会变成 8.8021839419922035E17。

    将 ID 作为数字发送是个坏主意,通常会将它们作为字符串发送。试试看 - 在 em 周围扔一些 "

    如果这不是问题所在,那么这个问题似乎无法回答:鉴于它正在与我们不知道的服务交谈,没有人可以重现这个问题,而且这个问题中的任何内容都没有给出明确的想法。黑暗中的野刺是我能给你的最好的。您比阅读此问题的任何人都了解更多信息:查找要包含的更多信息。

    【讨论】:

    • 这不是问题。 JSON 是有效的,因为我可以毫无问题地通过 CURL 发送 POST 请求。我只是无法授权
    • :\"880218394199220334\", 仍然值得一试,尽管 curl。
    • 但我会用引号括起来,谢谢
    猜你喜欢
    • 2022-01-16
    • 1970-01-01
    • 2015-03-08
    • 1970-01-01
    • 2020-11-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-15
    相关资源
    最近更新 更多