Java
Chilkat2 Java
Bunny Sign URL and then Download using Signed URL
See more Bunny CDN Examples
Shows how to sign a URL for BunnyCDN Token Authentication and then use it to download.Chilkat Java Downloads
import com.chilkatsoft.chilkat2.ChilkatException;
import com.chilkatsoft.chilkat2.DateTime;
import com.chilkatsoft.chilkat2.Http;
import com.chilkatsoft.chilkat2.StringBuilder;
import com.chilkatsoft.chilkat2.Url;
public class ChilkatExample {
public static void main(String[] args) {
// This example assumes the Chilkat API to have been previously unlocked.
// See Global Unlock Sample for sample code.
String mySecurityKey = "e7ea8d73-8fa0-44ef-a2cc-91526f7df5ed";
String url = "https://test.b-cdn.net/sample-pdf-with-images.pdf";
// Extract the URL components.
Url urlObj = new Url();
urlObj.parseUrl(url);
String url_scheme = "https";
if (!urlObj.getSsl()) {
url_scheme = "http";
}
String url_host = urlObj.getHost();
String url_path = urlObj.getPath();
// Calculate an expiration time 1 hour from the current date/time.
DateTime expTime = new DateTime();
expTime.setFromCurrentSystemTime();
expTime.addSeconds(3600);
String expires = expTime.getAsUnixTimeStr(false);
System.out.println("Expires = " + expires);
// Create the string to hash
StringBuilder sbToHash = new StringBuilder();
sbToHash.append(mySecurityKey);
sbToHash.append(url_path);
sbToHash.append(expires);
// Base64Url encoding is the same as base64, except "-" is used instead of "+",
// "_" is used instead of "/", and no "=" padding is added.
String token = sbToHash.getHash("sha256", "base64Url", "utf-8");
StringBuilder sbSignedUrl = new StringBuilder();
sbSignedUrl.append(url_scheme);
sbSignedUrl.append("://");
sbSignedUrl.append(url_host);
sbSignedUrl.append(url_path);
sbSignedUrl.append("?token=");
sbSignedUrl.append(token);
sbSignedUrl.append("&expires=");
sbSignedUrl.append(expires);
String signedUrl = sbSignedUrl.getAsString();
System.out.println("Signed URL: " + signedUrl);
// Use the signed URL to download the file.
Http http = new Http();
try {
http.download(signedUrl, "c:/aaworkarea/sample.pdf");
System.out.println("Success.");
} catch (ChilkatException e) {
System.out.println(e.getLastErrorText());
}
}
}