从 Forge mod 调用时,Discord webhook 返回错误

Discord webhook returnes error when called from Forge mod

我想要的是使用 java 代码通过 discord webhook 发送文件。

我使用从中获得的知识创建了一个完美的工作代码Whosebug post about curl requests in java and this Discord webhooks guide about sending attachments

问题是,如果我调用完全相同的代码,它在标准 java 程序中完美运行,而在 forge 1.8.9 mod 中运行,则会导致以下错误:

403: Forbidden
error code: 1010

有谁知道如何解决这个问题? Discord 如何区分两者?


以下是包含中心方法的代码。 LINE_FEEDaddFormFieldaddFilePart 直接来自提到的 Whosebug post 和 CHARSET = "UTF-8"channel_idtoken 是来自 Discord webhook 的自定义值。

public boolean sendFile(String username, String message, File file) {
    // mostly from 
    try {
        boundary = "===" + System.currentTimeMillis() + "===";
        URL url = new URL("https://discord.com/api/webhooks/" + channel_id + "/" + token);
        HttpsURLConnection urlConnection = (HttpsURLConnection) url.openConnection();
        urlConnection.setConnectTimeout(5000);
        urlConnection.setUseCaches(false);
        urlConnection.setDoOutput(true);
        urlConnection.setDoInput(true);
        urlConnection.setRequestProperty("content-type", "multipart/form-data; boundary=" + boundary);

        OutputStream os = urlConnection.getOutputStream();
        PrintWriter w = new PrintWriter(new OutputStreamWriter(os, CHARSET), true);
        if (message != null)
            addFormField(w, "payload_json",
                    "{\"username\": \"" + username + "\", \"content\": \"" + message + "\"}");
        else
            addFormField(w, "payload_json", "{\"username\": \"" + username + "\"}");
        addFilePart(os, w, "file", file);
        w.append(LINE_FEED).flush();
        w.append("--" + boundary + "--").append(LINE_FEED);
        w.close();
        os.close();
        int code = urlConnection.getResponseCode();

        // error handling
        System.out.println(code + ": " + urlConnection.getResponseMessage());
        BufferedReader br = new BufferedReader(new InputStreamReader(
                (code >= 100 && code < 400) ? urlConnection.getInputStream() : urlConnection.getErrorStream()));
        StringBuilder sb = new StringBuilder();
        String buffer;
        while ((buffer = br.readLine()) != null)
            sb.append(buffer);
        System.out.println(sb.toString());

        urlConnection.disconnect();
        return code >= 200 && code < 300;
    } catch (MalformedURLException ignored) {
        return false;
    } catch (IOException ignored) {
        return false;
    }
}

知道了! “Discord 如何区分两者”这个问题给了我将 user-agent 设置为固定值的想法 - 并解决了问题。

//[...]
urlConnection.setDoInput(true);
        
// this line solved the problem
urlConnection.setRequestProperty("user-agent", "Mozilla/5.0 ");

urlConnection.setRequestProperty("content-type", "multipart/form-data; boundary=" + boundary);
//[...]