Sample code for 30+ languages & platforms
Java

HTTP Download to Stream

See more REST Examples

Demonstrates how to stream the response body directly to a stream, which in this case is to a file stream.

Chilkat Java Downloads

Chilkat2 Java
import com.chilkatsoft.chilkat2.ChilkatException;
import com.chilkatsoft.chilkat2.Rest;
import com.chilkatsoft.chilkat2.Stream;
import com.chilkatsoft.chilkat2.Url;

public class ChilkatExample {

    public static void main(String[] args) {
        // This example requires the Chilkat API to have been previously unlocked.
        // See Global Unlock Sample for sample code.

        Rest rest = new Rest();

        // The URL we want to download is:
        // https://github.com/chilkatsoft/OAuth2-CSharp-Desktop/archive/master.zip
        Url url = new Url();
        url.parseUrl("https://github.com/chilkatsoft/OAuth2-CSharp-Desktop/archive/master.zip");

        // Connect to the web server
        boolean bAutoReconnect = true;
        try {
            rest.connect(url.getHost(), url.getPort(), url.getSsl(), bAutoReconnect);

            rest.sendReqNoBody("GET", url.getPath());
        } catch (ChilkatException e) {
            System.out.println(e.getLastErrorText());
            return;
        }

        // Read the response header.
        int responseStatusCode = rest.readResponseHeader();
        if (responseStatusCode < 0) {
            System.out.println(rest.getLastErrorText());
            return;
        }

        System.out.println("Response status code = " + responseStatusCode);

        // We expect a 200 response status if the file data is coming.
        // Otherwise, we'll get a string response body with an error message(or no response body).
        if (responseStatusCode == 200) {
            Stream bodyStream = new Stream();

            // The stream's sink will be a file.
            bodyStream.setSinkFile("qa_output/OAuth2-CSharp-Desktop/archive/master.zip");

            // Read the response body to the stream.  Given that we've
            // set the stream's sink to a file, it will stream directly
            // to the file.
            try {
                rest.readRespBodyStream(bodyStream, true);
            } catch (ChilkatException e) {
                System.out.println(e.getLastErrorText());
                return;
            }

            System.out.println("Successfully downloaded the file.");
        } else {
            String errResponse = null;
            try {
                errResponse = rest.readRespBodyString();
                System.out.println(errResponse);
            } catch (ChilkatException e) {
                System.out.println(e.getLastErrorText());
            }
        }
    }
}