gpt4 book ai didi

java - 无法使用java下载文件

转载 作者:行者123 更新时间:2023-11-29 06:33:37 25 4
gpt4 key购买 nike

我正在尝试从 highcharts.com 下载 javascript 库。如果我手动点击 url,我就能看到该文件。但是如果我用我的程序尝试它,它会返回 403 错误。我可以下载其他 js 文件,但不能下载 highcharts。这是我的代码。

try {


String fileName = "highchartsjs"; //The file that will be saved on your computer
URL link = new URL("http://code.highcharts.com/highcharts.js"); //The file that you want to download
//Code to download
InputStream in = new BufferedInputStream(link.openStream());
ByteArrayOutputStream out = new ByteArrayOutputStream();
byte[] buf = new byte[1024];
int n = 0;
while (-1!=(n=in.read(buf)))
{
out.write(buf, 0, n);
}
out.close();
in.close();
byte[] response = out.toByteArray();

FileOutputStream fos = new FileOutputStream(fileName);
fos.write(response);
fos.close();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}

我遇到了非常奇怪的错误。让我知道我哪里出错了,或者他们添加了我们不能通过程序等下载的政策。谢谢期待。

添加异常跟踪以供引用:

java.io.IOException: Server returned HTTP response code: 403 for URL: http://code.highcharts.com/highcharts.js
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(Unknown Source)
at java.net.URL.openStream(Unknown Source)
at com.visualbi.readjson.SaveMap.downloadFiles(SaveMap.java:52)
at com.visualbi.Boot.main(Boot.java:11)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at com.simontuffs.onejar.Boot.run(Boot.java:340)
at com.simontuffs.onejar.Boot.main(Boot.java:166)

最佳答案

您还可以使用 HttpClient:http://hc.apache.org/

HttpClient client = HttpClientBuilder.create().build();
HttpGet request = new HttpGet(url);
HttpResponse response = client.execute(request);
BufferedReader rd = new BufferedReader(new InputStreamReader(response
.getEntity().getContent()));
StringBuffer result = new StringBuffer();
String line = "";
while ((line = rd.readLine()) != null) {
result.append(line);
}
FileOutputStream fos = new FileOutputStream(fileName);
fos.write(result.toString().getBytes());
fos.close();

关于java - 无法使用java下载文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26191801/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com