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:已连接”,我在编程时是新手,但我没有任何Ideia的原因
最佳答案
由于您正在使用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();
}
也可以看看:
InputStream.transferTo(OutputStream)
FileOutputStream
OkHttpClient