我有一个包含以下详细信息的 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(...)
并添加您的输出目录。
What happens here?
Get filename from URL:
url.substring(url.lastIndexOf('/') + 1)
.In order to download the file, you need to read it first.
InputStream
.Once you've read it by
URI.create(url).toURL().openStream()
.We save what we've read in our stream to disk using
Files.copy(...)
关于java - 如何下载 REST API 响应文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60090251/