Java Reference
In-Depth Information
public
public static
static SSLSocketFactory
getFactory ( File pKeyFile , String pKeyPassword )
throws
throws Exception {
KeyManagerFactory keyManagerFactory =
KeyManagerFactory . getInstance ( "SunX509" );
KeyStore keyStore = KeyStore . getInstance ( "PKCS12" );
InputStream keyInput = new
new FileInputStream ( pKeyFile );
keyStore . load ( keyInput , pKeyPassword . toCharArray ());
keyInput . close ();
keyManagerFactory . init ( keyStore , pKeyPassword . toCharArray ());
SSLContext context = SSLContext . getInstance ( "TLS" );
context . init ( keyManagerFactory . getKeyManagers (), null
null
, new
new SecureRandom ());
return
return context . getSocketFactory ();
}
This code loads the truststore into memory and creates an SSLSocketFactory . The factory
can then be registered with a java.net.ssl.HttpsURLConnection :
public
public static
static void
void main ( String args []) throws
throws Exception {
URL url = new
new URL ( "https://someurl" );
HttpsURLConnection con = ( HttpsURLConnection ) url . openConnection ();
con . setSSLSocketFactory ( getFactory ( new
new File ( "cacerts.jks" ),
"changeit" ));
}
}
You may then make invocations to the URL, and the client certificate will be used for au-
thentication.
Advantages and Disadvantages
The biggest advantage of using the java.net package as a RESTful client is that it is built in
to the JDK. You don't need to download and install a different client framework.
There are a few disadvantages to the java.net API. First, it is not JAX-RS-aware. You will
have to do your own stream processing and will not be able to take advantage of any of the
MessageBodyReaders and MessageBodyWriters that come with your JAX-RS implementa-
tion.
Search WWH ::




Custom Search