简体   繁体   中英

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();
            }

I'm Trying to Transfer the Image in the URL(Discord) to a File but i get an Error "java.lang.IllegalStateException: Already connected" i'm new at Programming and i don't have any Ideia why this is Occurring

Since you are using JDA you can take advantage of the http client it uses:

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();
}

See also:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM