如何下载 REST API 响应文件?



我有一个包含以下详细信息的API:

GET /REST/sql_snapshot/2003-03-01.sql.gz
HTTP/1.1 Host: api.application.cap.cams.net
Authorization: Basic asdwqfasft
The response from API shown below omits the message body, which contains binary compressed SQL data.
HTTP/1.1 200 OK
Date: Wed, 05 Mar 2003 10:19:46 GMT
Server: Apache/1.3.22 (Unix) (Red-Hat/Linux)
Content-Type: application/octet-stream

我最初有这段代码

URL location = new URL("https://api.application.cap.cams.net/REST/sql_snapshot/2003-03-01.sql.gz");
HttpsURLConnection connection = (HttpsURLConnection) location.openConnection();
connection.setHostnameVerifier(HostnameVerifierFactory getHostnameVerifier());
connection.setSSLSocketFactory(SSLConfigurerFactory.getConfigurer().getSSLSocketFactory());
connection.connect();
// after this I will retrieve the input stream of the connection. Then write the file (zip file).

我做错了什么,因为我无法获取输入流,因为连接的响应代码是 -1。我知道这个响应代码,但我不完全确定我是如何得到这个的。这是从 REST API 调用检索和下载文件的正确方法吗?

在您的情况下,您只想下载文件,而不必担心进行休息调用。您可以执行以下操作(不需要外部库(:

import java.io.InputStream; 
import java.net.URI; 
import java.nio.file.Files; 
import java.nio.file.Paths;
...
public void downloadFile(String url) {
try (InputStream inputStream = URI.create(url).toURL().openStream()) {
Files.copy(inputStream, Paths.get(url.substring(url.lastIndexOf('/') + 1)));
}catch(Exception ex) {
ex.printStackTrace();
}
}

用法:

downloadFile("https://api.application.cap.cams.net/REST/sql_snapshot/2003-03-01.sql.gz")

节省:

2003-03-01.sql.gz

这会将文件保存在与项目相同的目录中。如果要将其放置在特定位置,则必须修改Paths.get(...)并添加输出目录。

这里发生了什么?

从网址获取文件名:url.substring(url.lastIndexOf('/') + 1)

为了下载文件,您需要先阅读它。InputStream.

一旦你读完了它URI.create(url).toURL().openStream().

我们使用Files.copy(...)将流中读取的内容保存到磁盘

最新更新