Sample code for 30+ languages & platforms
Java

Example: Http.DownloadAppend method

Demonstrates the DownloadAppend method.

Chilkat Java Downloads

Chilkat2 Java
import com.chilkatsoft.chilkat2.FileAccess;
import com.chilkatsoft.chilkat2.Http;
import com.chilkatsoft.chilkat2.StringBuilder;

public class ChilkatExample {

    public static void main(String[] args) {
        String targetPath = "c:/temp/qa_output/download.txt";

        Http http = new Http();
        http.setKeepResponseBody(true);

        // Assume the target file in the local filesystem does not yet exist.
        http.downloadAppend("https://chilkatsoft.com/testData/helloWorld.txt", targetPath);
        int statusCode = http.getLastStatus();
        if (statusCode == 0) {
            // Unable to either send the request or get the response.
            System.out.println(http.getLastErrorText());
            return;
        }

        // Should be 200.
        System.out.println("Response status code: " + statusCode);

        // Examine the contents of the file.
        StringBuilder sb = new StringBuilder();
        sb.loadFile(targetPath, "utf-8");
        System.out.println(sb.getAsString());

        // Output:
        // Response status code: 200
        // Hello World!

        // Download another text file and append to the target file.
        http.downloadAppend("https://chilkatsoft.com/testData/this_is_a_test.txt", targetPath);
        statusCode = http.getLastStatus();
        if (statusCode == 0) {
            // Unable to either send the request or get the response.
            System.out.println(http.getLastErrorText());
            return;
        }

        // Should be 200.
        System.out.println("Response status code: " + statusCode);

        // Examine the contents of the file.
        sb.loadFile(targetPath, "utf-8");
        System.out.println(sb.getAsString());

        // Output:
        // Response status code: 200
        // Hello World!This is a Test.

        // Delete the local target file.
        FileAccess fac = new FileAccess();
        fac.fileDelete(targetPath);

        // Try to download a file that does not exist:
        http.downloadAppend("https://chilkatsoft.com/testData/does_not_exist.txt", targetPath);
        statusCode = http.getLastStatus();
        if (statusCode == 0) {
            // Unable to either send the request or get the response.
            System.out.println(http.getLastErrorText());
        } else {
            // We got a response, and we already know it wasn't a 200 success response.
            // It should be a 404 not found.
            System.out.println("Response status code: " + statusCode);
            // Examine the response body.
            System.out.println("Response body:");
            System.out.println(http.getLastResponseBody());
        }
    }
}