private void getCertificate() throws IOException
	{
		try
		{
			SavingTrustManager tm = openSocketWithCert();
			
			// Try to handshake the socket
			boolean success = false;
			try
			{
				sslsocket.startHandshake();
				success = true;
			}
			catch (SSLException e)
			{
				sslsocket.close();
			}
			
			// If we failed to handshake, save the certificate we got and try again
			if (!success)
			{
				// Set up the directory if needed
				File dir = new File("certs");
				if (!dir.isDirectory())
				{
					dir.delete();
					dir.mkdir();
				}
				
				// Reload (default) KeyStore
				KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
				File file = new File(System.getProperty("java.home") + "/lib/security/cacerts");
				
				InputStream in = new FileInputStream(file);
				ks.load(in, passphrase);
				
				// Add certificate
				X509Certificate[] chain = tm.chain;
				if (chain == null)
					throw new Exception("Failed to obtain server certificate chain");
				
				X509Certificate cert = chain[0];
				String alias = server + "-1";
				ks.setCertificateEntry(alias, cert);
				
				// Save certificate
				OutputStream out = new FileOutputStream("certs/" + server + ".cert");
				ks.store(out, passphrase);
				out.close();
				System.out.println("Installed cert for " + server);
			}
		}
		catch (Exception e)
		{
			// Hitting an exception here is very bad since we probably won't recover
			// (unless it's a connectivity issue)

			// Rethrow as an IOException
			throw new IOException(e.getMessage());
		}
	}