Java Reference
In-Depth Information
Listing 5.2: Download Authenticated URL (AuthDownloadURL.java)
package com.heatonresearch.httprecipes.ch5.recipe2;
import java.net.*;
import java.io.*;
public class AuthDownloadURL
{
public static int BUFFER_SIZE = 8192;
/**
* Download either a text or binary file from a URL.
* The URL's headers will be scanned to determine the
* type of tile.
*
* @param remoteURL The URL to download from.
* @param localFile The local file to save to.
* @throws IOException Exception while downloading.
*/
public void download(URL remoteURL, File localFile,
String uid, String pwd)
throws IOException
{
HttpURLConnection http = (
HttpURLConnection) remoteURL.openConnection();
addAuthHeader(http, uid, pwd);
InputStream is = http.getInputStream();
OutputStream os = new FileOutputStream(localFile);
String type =
http.getHeaderField("Content-Type").toLowerCase().trim();
if (type.startsWith("text"))
downloadText(is, os);
else
downloadBinary(is, os);
is.close();
os.close();
http.disconnect();
}
/**
* Add HTTP authntication headers to the specified
* HttpURLConnection
* object.
* @param http The HTTP connection.
* @param uid The user id.
* @param pwd The password.
Search WWH ::




Custom Search