HeyHelp
HeyHelp

Reputation: 1

How to download REST API response file?

I have an API with these details:

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

I have this snippet of code initially

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).

Am I doing something wrong because I'm not able to get the input stream since the response code of the connection is -1. I know this response code but I'm not entirely sure how I got this. Is this the correct way to retrieve and download the file from a REST API call?

Upvotes: 0

Views: 1977

Answers (1)

Joel
Joel

Reputation: 6173

In your case, you just want to download the file and you don't have to worry about making rest-calls. You can do something like this (No external libraries are needed):

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();
    }
}

Usage:

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

Saves:

2003-03-01.sql.gz

This will save the file in the same directory as your project. If you want to place it in a specific place, you will have to modify Paths.get(...) and add your output-directory.

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(...)

Upvotes: 1

Related Questions