我有一个具有以下详细信息的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调用中检索和下载文件的正确方法吗?
答案 0 :(得分:1)
对于您而言,您只想下载文件,而不必担心拨打电话。您可以执行以下操作(不需要外部库):
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
url.substring(url.lastIndexOf('/') + 1)
获取文件名。要下载文件,您需要先阅读它。
InputStream
。一旦您读过
URI.create(url).toURL().openStream()
。我们使用
将流中已读取的内容保存到磁盘中Files.copy(...)