Niks
Niks

Reputation: 4832

Optimize HTTPS connection in Java client

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?

Upvotes: 0

Views: 1714

Answers (2)

ok2c
ok2c

Reputation: 27528

You could also try to use HttpCore instead of HttpClient. HttpCore is a set of HTTP transport components HttpClient is based upon. It has been specifically optimized for low memory footprint as well as performance. It lacks higher level HTTP functionality provided by HttpClient (connection management, cookie & state management, authentication) but should be quite efficient in terms of memory utilization.

http://hc.apache.org/httpcomponents-core-ga/examples.html

Upvotes: 1

Kevin
Kevin

Reputation: 25269

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.

Upvotes: 2

Related Questions