Reputation:
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
Upvotes: 1
Views: 152
Reputation: 6131
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:
Upvotes: 0