开发者

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 A开发者_StackOverflow中文版pache 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.


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜