I want to call a secure webservice, using a cert that I have... the server takes a long time to authenticate with the cert, and, while this is ok the first time, the user will call it over and over again (in the same "session") and I feel I ought to be able to reuse the connection.
I have the following code.
System.setProperty("javax.net.ssl.trustStorePassword", "");
System.setProperty("javax.net.ssl.trustStore", "trusted.cacerts");
System.setProperty("javax.net.ssl.keyStorePassword", "mypassword");
System.setProperty("javax.net.ssl.keyStore", "trusted.clientcerts");
URL url = new URL("https://remoteserver:8443/testservice");
HttpsURLConnection connection = (HttpsURLConnection)url.openConnection();
connection.setInstanceFollowRedirects(false);
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "text/xml");
connection.setDoOutput(true);
OutputStream os = connection.getOutputStream();
os.write(bytes);
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
connection.disconnect();
This works great... but is slow. Just the authentication takes about 10 seconds. This internal authentication is typical here and that cannot be sped up. But can't I reuse it somehow?
I tried put a loop around this code, between theurl.connection
and the disconnect, thinking I could just recall it again and again, but that fails (500). I have tried moving things around a bit, in order to do only some of the commands the first time, but it still fails.
I read about keep-alive, but have not found any good examples of what this is, and how to use it (if that is even a valid way). 开发者_C百科If I do all of this via HTML, via Firefox or IE, the browser is able to cache the cert, I guess, so every time after the first is blazing fast. Can I emulate that some how?better alternative is to use HttpClient and its connection pooling mechanism. also see if https keep-alive is going to help you
Try just not calling connection.disconnect()
... I don't think there should be any need for you to do that. You should, however, ensure that you close your reader
when you're finished with it.
精彩评论