I’m trying to communicate with a RESTful API over SSL. The whole client application relies on a basic connection method which looks something like this
URL url = null;
HttpsURLConnection connection = null;
BufferedReader bufferedReader = null;
InputStream is = null;
try {
url = new URL(TARGET_URL);
HostnameVerifier hv = new HostnameVerifier() {
public boolean verify(String urlHostName, SSLSession session) {
return true;
}
};
HttpsURLConnection.setDefaultHostnameVerifier(hv);
connection = (HttpsURLConnection) url.openConnection();
connection.setRequestMethod(requestType);
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.setRequestProperty("Content-Language", "en-US");
connection.setSSLSocketFactory(sslSocketFactory);
is = connection.getInputStream();
bufferedReader = new BufferedReader(new InputStreamReader(is));
String line;
StringBuffer lines = new StringBuffer();
while ((line = bufferedReader.readLine()) != null) {
lines.append(line).append(LINE_BREAKER);
}
return lines.toString();
} catch (Exception e) {
System.out.println("Exception is :"+e.toString());
return e.toString();
}
}
This works well, but is there a more efficient way? We’ve tried Apache HTTPClient. It has an awesomely simple API but when we compared the performance of the above code vs Apache HTTPClient with YourKit, the latter one was creating more objects than the first. How do I optimize this?
I’ve used HTTPClient (but not for HTTPS) but I think this applies to your case. The recommendation is to create a single HTTPClient for your server, and a new HTTPGet object per call. You’ll want to specify the multi-threaded client connection manager with an appropriate number of connections to allocate per host, and max total connections when you initialize your HTTPClient.