File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Sockets and Internet Protocols and the fly likes How to attach a certificate to a socket and send a https POST request? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Sockets and Internet Protocols
Bookmark "How to attach a certificate to a socket and send a https POST request?" Watch "How to attach a certificate to a socket and send a https POST request?" New topic
Author

How to attach a certificate to a socket and send a https POST request?

Dan MacLeod
Ranch Hand

Joined: Mar 19, 2009
Posts: 30
I need to create a socket and attached a certificate to it. Once I do this, I need to send a https POST request. Below is the code I'm trying to get to work, but when I try to connect to the host I get a UnknownHostException. The exception occurs on this line: httpURLConn.connect();

thanks
Dan


public class AidapRequest {

static String POST = "POST";
static String TYPE = "Content-type:";
static String LEN = "Content-length:";
static String ENC = "Accept-Encoding:";
static String testcaseDir = "d:\\AIDAP\\requests";
static String resultsDir = "d:\\AIDAP\\responses";
static String testcaseFile = "testing";
static String urlString = "https://www.aidaptest.naimes.faa.gov/";
//static String urlString = "https://www.aidaptest.naimes.faa.gov/aidap/XmlNotamServlet";
//static String urlString = "";

// instance variables
boolean useGZIP = false;
static String postLine = "";
static String typeLine = "";
static String lenLine = "";
static String encodeLine = "";
static String queryLine = "";
static String keyStorePath = "D:\\Applications\\AA\\NMS\\aidap-collector\\aidapModule\\config\\properties\\aidapuser_1f5d_2011_03_1192.pfx";
//static String keyStorePswd = "start123";
static String keyStorePswd = "UB#20abba";

/**
* Main Method
* @param args
*
*/
public static void main(String args[]) {

if (!readTC()) {
System.exit(-1);
}

HttpURLConnection httpURLConn = null;
BufferedOutputStream bos = null;
InputStream is = null;
URL url = null;

try {

// Setup connection
System.out.println("Accessing - " + urlString);
//urlString = postLine.substring(postLine.indexOf(POST) + POST.length(), postLine.indexOf("HTTP")).trim();
url = new URL(urlString);

// HTTPS connection
httpURLConn = (HttpURLConnection) url.openConnection();

// HTTPS (with client certificate)
if (httpURLConn instanceof HttpsURLConnection) {

// take care of server certificate does match hostname
HostnameVerifier hv = new HostnameVerifier() {

public boolean verify(String hostname,
SSLSession session) {
return true;
}

public boolean verify(String hostname, String temp) {
return true;
}
};

((HttpsURLConnection) httpURLConn).setHostnameVerifier(hv);

// set to always trust the server
X509TrustManager tm = new X509TrustManager() {

public void checkClientTrusted(X509Certificate[] arg0,
String arg1)
throws CertificateException {
}

public void checkServerTrusted(X509Certificate[] arg0,
String arg1)
throws CertificateException {
}

public X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[0];
}

public boolean isClientTrusted(X509Certificate[] arg0) {
return true;
}

public boolean isServerTrusted(X509Certificate[] arg0) {
return true;
}
};

// use the client certificate
KeyStore ks = KeyStore.getInstance("PKCS12");
ks.load(new FileInputStream(new File(keyStorePath)),
keyStorePswd.toCharArray());

KeyManagerFactory kmf =
KeyManagerFactory.getInstance("SunX509");
kmf.init(ks, keyStorePswd.toCharArray());

// Set socket context and setup socket factory
SSLContext context = SSLContext.getInstance("TLS");
context.init(kmf.getKeyManagers(),
new TrustManager[]{tm},
null);

SSLSocketFactory sockFactory = context.getSocketFactory();
((HttpsURLConnection) httpURLConn).setSSLSocketFactory(sockFactory);
} else {
System.err.println("Go - else not https");
}


// Set up request parameters
httpURLConn.setAllowUserInteraction(false);
httpURLConn.setDoInput(true);
httpURLConn.setDoOutput(true);
httpURLConn.setUseCaches(false);
httpURLConn.setRequestProperty(typeLine.substring(0, typeLine.indexOf(":")).trim(),
typeLine.substring(typeLine.indexOf(":") + 1).trim());
//if (!encodeLine.equals("")) {
// httpURLConn.setRequestProperty(encodeLine.substring(0, encodeLine.indexOf(":")).trim(),
// encodeLine.substring(encodeLine.indexOf(":") + 1).trim());
//}
httpURLConn.setRequestMethod(POST);
if (queryLine == null || queryLine.length() == 0) {
httpURLConn.setRequestMethod("GET");
}

// Connect to server
System.out.println("Connecting to server...");
httpURLConn.connect();

System.out.println("Send request to server");
// Write HTTP Request
if (queryLine.length() > 0) {
bos = new BufferedOutputStream(httpURLConn.getOutputStream());
byte[] buf = queryLine.getBytes();
bos.write(buf, 0, buf.length);
bos.flush();
}

//Read HTTP Response
System.out.println("Read response from server...");
is = new BufferedInputStream(httpURLConn.getInputStream());

// read-in appropriately based on whether returned data
// has content encoding gzip
String contentEncoding = httpURLConn.getContentEncoding();
if (contentEncoding != null && contentEncoding.equalsIgnoreCase("gzip")) {
try {
if (is.markSupported()) {
is.mark(2);
}
is = new GZIPInputStream(is);
} catch (IOException e) {
if (is.markSupported()) {
is.reset();
}
is = new BufferedInputStream(is);
}
}

// Read the response in
System.out.println("Starting read");
byte[] buff = new byte[8192];
int numOfBytes;
boolean downloading = true;
int loaded = 0;

FileOutputStream fileWriter = new FileOutputStream(resultsDir + "\\" + testcaseFile + "_out.txt");
System.out.println("Start write");
while ((numOfBytes = is.read(buff)) > 0) {
fileWriter.write(buff, 0, numOfBytes);
}
fileWriter.close();

System.err.println("End of run");

} catch (IOException e) {
System.err.println("io error: " + e.getMessage());
e.printStackTrace();
} catch (Exception e) {
System.err.println("exception: " + e.getMessage());
e.printStackTrace();
} finally {
// Close input stream
if (is != null) {
try {
is.close();
} catch (IOException e) {
}
is = null;
}
// Close output stream
if (bos != null) {
try {
bos.close();
} catch (IOException e) {
}
bos = null;
}
// Close connection
if (httpURLConn != null) {
httpURLConn.disconnect();
httpURLConn = null;
}
}
} //end of go()


/**
*
* @return
*/
private static boolean readTC() {

postLine = "POST /aidap/XmlNotamServlet HTTP/1.1";
typeLine = "Content-type: application/x-www-form-urlencoded";
lenLine = "Content-length: <input_parameter’s length>";
encodeLine = "Accept-Encoding: gzip";
queryLine = "uid=AAITSTST&password=xxxx&location_id=KDFW";
return true;
}

}
Padhrig McCarthy
Greenhorn

Joined: Nov 25, 2009
Posts: 1
There is more to this than just getting the code right -- one has to manage public and private keys. See this web page for a complete description of the process, and some code that will connect to the server:

http://rap.ucar.edu/~paddy/cacerts/index.html
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: How to attach a certificate to a socket and send a https POST request?