java.lang.IllegalStateException:已经连接(Discord JDA)

java.lang.IllegalStateException: Already connected(Discord JDA)

            URL uImg;
            File fImg = new File("img.png");
            try {
                uImg = new URL(msg.getAuthor().getAvatarUrl());
                URLConnection uc = uImg.openConnection();
                uc.connect();
                uc.addRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0)");
                FileUtils.copyURLToFile(uImg, fImg);
            } catch (IOException e) {
                e.printStackTrace();
            }

我正在尝试将 URL(Discord) 中的图像传输到文件,但出现错误 "java.lang.IllegalStateException: Already connected" 我是编程新手,我没有任何想法为什么会发生这种情况

由于您使用的是 JDA,因此您可以利用它使用的 http 客户端:

OkHttpClient http = jda.getHttpClient(); // getHttpClient since JDA 4.0.0
Request req = new Request.Builder()
            .url(avatarUrl)
            .addHeader("User-Agent", "DiscordBot")
            .build();
try (Response r = http.newCall(req).execute();
     FileOutputStream fileOut = new FileOutputStream(file)) {
    r.body().byteStream().transferTo(fileOut); // transferTo since java 9
} catch (IOException e) {
    e.printStackTrace();
}

另请参阅: