On This Page
Sample Code for Basic Authentication
The sample below shows how you can upload a batch file to a batch server using Basic Authentication.
import java.util.*;import java.io.*;import javax.net.ssl.*;import java.security.*;public class SSLFileTransfer {Properties props = new Properties(); // stores properties from property file/*** Default constructor*/public SSLFileTransfer() {}/*** Initialize program by reading properties file.** @param propsFile needed for file transfer*/public void init(String propsFile) {try {props.load(new BufferedInputStream(new FileInputStream(new File(propsFile))));} catch (Exception e) {e.printStackTrace();System.exit(-1);}}/*** Error message if incorrect arguments are passed.*/public static void usage() {System.out.println("USAGE: java SSLFileTransfer <full path property file name>");System.exit(-1);}/*** Get factory for authentication** @throws IOException if exception occurs*/private SSLSocketFactory getFactory() throws IOException {try {SSLContext ctx;KeyManagerFactory kmf;KeyStore ks, ks1;char[] passphrase = props.getProperty("passPhrase").toCharArray();ctx = SSLContext.getInstance("TLSv1.2");kmf = KeyManagerFactory.getInstance("SunX509");ks = KeyStore.getInstance("PKCS12");ks1 = KeyStore.getInstance("JKS");ks.load(new FileInputStream(props.getProperty("key")), passphrase);ks1.load(new FileInputStream(props.getProperty("keyStore")), passphrase);kmf.init(ks, passphrase);TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509");tmf.init(ks1);ctx.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);return ctx.getSocketFactory();} catch (Exception e) {e.printStackTrace();throw new IOException(e.getMessage());}}/*** Get host from property file*/private String getHost() {return props.getProperty("host", "localhost");}/*** Get port from property file*/private int getPort() {return Integer.parseInt(props.getProperty("port"));}/*** Send request (file) to the server.** @param out outstream to send the data to the server* @throws Exception if an error occurs.*/private void sendRequest(PrintWriter out) throws Exception {final String CRLF = "\r\n";String path = props.getProperty("path");out.print("POST " + path + " HTTP/1.1" + CRLF);final String BOUNDARY = "7d03135102b8";out.print("Host: " + props.getProperty("host") + CRLF);out.print("Content-Type: multipart/form-data; boundary="+BOUNDARY+CRLF);String uploadFile = props.getProperty("uploadFile");String authString = props.getProperty("bcUserName") + ":" + props.getProperty("bcPassword");String encodedAuthString = "Basic " + new sun.misc.BASE64Encoder().encode(authString.getBytes ());out.print("Authorization: " + encodedAuthString+CRLF);StringBuffer sbuf = new StringBuffer();sbuf.append("--"+BOUNDARY+CRLF);sbuf.append("Content-Disposition: form-data; name=\"upfile\"; filename=\"" + uploadFile + "\""+CRLF);sbuf.append("Content-Type: text/plain"+CRLF+CRLF);char[] buf;int cnt;FileReader fi = new FileReader(uploadFile);try {buf = new char[1024000];cnt = fi.read(buf);} finally {fi.close();}sbuf.append(buf, 0, cnt);sbuf.append(CRLF);sbuf.append("--"+BOUNDARY+"--"+CRLF);int sz = sbuf.length();out.print("Content-Length: "+ sz+CRLF);out.print(CRLF);out.print(sbuf);out.flush();// Make sure there were no surprisesif (out.checkError()) {System.out.println("SSLFileTransfer: java.io.PrintWriter error");}}/*** Reads the response from the server.* @param in instream to get the data from the server* @throws Exception if an error occurs.*/private void readResponse(BufferedReader in) throws Exception {boolean successful = false;String inputLine;while ((inputLine = in.readLine()) != null) {if (inputLine.startsWith("HTTP") && inputLine.indexOf("200") >= 0) {successful = true;}System.out.println(inputLine);}System.out.println("UPLOAD FILE " + (successful? "SUCCESSFUL" : "FAILED") + "!!!\n");}/*** Upload file to the server.* @throws Exception if an error occurs.*/public void upload() throws Exception {try {SSLSocketFactory factory = getFactory();SSLSocket socket = (SSLSocket)factory.createSocket(getHost(), getPort());PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())));BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));socket.startHandshake();sendRequest(out);readResponse(in);out.close();in.close();socket.close();} catch (Exception e) {e.printStackTrace();throw e;}}/*** Main method to start file transfer* @param args command line arguments (property file, see usage())* @throws Exception if an error occurs.*/public static void main(String[] args) throws Exception {if (args == null || args.length != 1) {usage();}SSLFileTransfer fileXfer = new SSLFileTransfer();fileXfer.init(args[0]);fileXfer.upload();}}