`

Make sure to release the connection before allocating another one

 
阅读更多

自从HttpClient升级到HttpComponent后,HttpMethod提供的方法releaseConnection()就被丢弃了。
转而改成另外相对麻烦点的维护一个连接池的处理方式。

When you replace Apache Commons HttpClient with Apache HttpComponents.
if you haven’t release connection in your codes, you may found exception traces like:

java.lang.IllegalStateException: Invalid use of SingleClientConnManager: connection still allocated.
Make sure to release the connection before allocating another one.
        at org.apache.http.impl.conn.SingleClientConnManager.getConnection(SingleClientConnManager.java:199)
        at org.apache.http.impl.conn.SingleClientConnManager$1.getConnection(SingleClientConnManager.java:173)
        at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:390)
        at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:641)
        at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:576)
        at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:554)
 But HttpComponents doesn’t provide method like void org.apache.commons.httpclient.HttpMethod.releaseConnection().

It provides another method to do this work. And it’s more complex then before. Sample codes I wrote below:

public class Test {
    public static void main(String[] args) throws Exception {
        System.setProperty("org.apache.commons.logging.simplelog.log.httpclient.wire", "debug");
        System.setProperty("org.apache.commons.logging.simplelog.log.org.apache.commons.httpclient", "debug");
        System.setProperty("org.apache.commons.logging.Log", "org.apache.commons.logging.impl.SimpleLog");
        System.setProperty("org.apache.commons.logging.simplelog.showdatetime", "true");
        System.setProperty("org.apache.commons.logging.simplelog.log.org.apache.http", "debug");
 
        HttpParams httpParams = new BasicHttpParams();
        httpParams.setIntParameter(ConnManagerPNames.MAX_TOTAL_CONNECTIONS, 20);
        SchemeRegistry schreg = new SchemeRegistry();
        schreg.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
        schreg.register(new Scheme("https", PlainSocketFactory.getSocketFactory(), 443));
        ThreadSafeClientConnManager connManager = new ThreadSafeClientConnManager(httpParams, schreg);
//        connManager.setMaxTotal(20);
         
        DefaultHttpClient client = new DefaultHttpClient(connManager, httpParams);
        String url = "http://www.google.com/";
        HttpGet get = new HttpGet(url);
        sendRequest(get, client);
        System.out.println("------------------2------------------");
        sendRequest(get, client);
        System.out.println("------------------3------------------");
        sendRequest(get, client);
        System.out.println("------------------4------------------");
        sendRequest(get, client);
        System.out.println("------------------5------------------");
        sendRequest(get, client);
    }
 
    private static void sendRequest(HttpGet get, DefaultHttpClient client) throws InterruptedException {
        HttpResponse resp = null;
        try {
            resp = client.execute(get);
            // get response content here
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                resp.getEntity().getContent().close(); //!!!IMPORTANT
            } catch (Exception e) {
                // go to hell
            }
        }
    }
}
 Here are some notes:
  1. HC4.1 may deprecated some methods/properties.
  2. DON’T FORGET TO CLOSE THE RESPONSE STREAM
  3. 转自: http://blog.blacklee.net/tech/707-release-connection-in-apache-httpcomponents
分享到:
评论
2 楼 woxiangbo 2013-02-06  
http://foo.jasonhudgins.com/2010/03/http-connections-revisited.html
1 楼 woxiangbo 2013-02-06  
发现在finally中 getContent.close()也不是很管用,功夫不负有心人,发现是线程安全的问题,在DefaultHttpClient 初始化的时候,做如下设置:

DefaultHttpClient client = new DefaultHttpClient();
    ClientConnectionManager mgr = client.getConnectionManager();
    HttpParams params = client.getParams();
 
    client = new DefaultHttpClient(
        new ThreadSafeClientConnManager(params,
            mgr.getSchemeRegistry()), params);

相关推荐

    微软内部资料-SQL性能优化2

    Before we look at how SQL Server uses and manages its memory, we need to ensure a full understanding of the more common memory related terms. The following definitions will help you understand how SQL...

    MS-DOS 5.0

    Make sure that you can access all your hard-disk partitions. 4. If you can access all the partitions, insert the floppy disk that contains the SYS.COM file into drive a: and type the following ...

    BUS Hound

    The data can now be dragged using the mouse to another product. <br>Pressing control-c copies the selected lines to the clipboard. <br>Command Overlap <br>Overlapped commands are identified ...

    C# - CSharp 12 in a Nutshell The Definitive Reference

    One of the core features of C# is its type safety, which ensures that variables can only hold values of the types they were declared to hold. This helps prevent runtime errors and makes the code more ...

    Springer.The.Developer’s.Guide.to.Debugging.2008.pdf

    8.2.4 Use strace to Trace Calls to the OS . . . . . 104 8.3 Compilers and Debuggers have Bugs too . . . . . . . . 106 8.3.1 Compiler Bugs . . . . . . . . . 106 8.3.2 Debugger and Compiler ...

    cli guide and Reference

    This involves allocating handles and setting up the connection to the database. - **Handles in CLI**: Handles are used to manage resources such as connections, statements, and descriptors. They ...

    IOS5 Programming Cookbook

    - **Typecasting Basics**: Typecasting is used to convert one type to another. In Objective-C, typecasting can be necessary when working with generic collections or interoperating with C code. - **...

    Multiple-Bits-Slot Reservation Aloha Protocol for Tag Identification

    protocol, the reader assigns reservation slots before allocating frame slots, and each tag generates a random sequence in its own reservation slot randomly selected by this tag to reserve a frame slot...

    Salesforce.Reporting.and.Dashboards.178439467X

    This book starts with an overview of the entire Salesforce technology and then moves on to the more important topics of allocating permissions and choosing the correct reports to improve efficiency. ...

    APICS DICTIONARY

    Setting an appropriate AQL helps in ensuring that products meet the required quality levels before release, reducing the likelihood of defects and customer complaints. This is particularly important ...

    C Programming

    - **Neater Printing**: Techniques for formatting output using `printf` to make the presentation of results more readable. #### Functions This part of the document explains functions in C, which are ...

    Advanced Programming in the UNIX Environment

    Typical services include executing a new program, opening a file, reading a file, allocating a region of memory, getting the current time of day, and so on. The focus of this text is to describe the ...

    The Art of Assembly Language Programming

    The 80x86 MOV Instruction 4.8 - Some Final Comments on the MOV Instructions <br>4.9 Laboratory Exercises 4.9.1 The UCR Standard Library for 80x86 Assembly Language Programmers 4.9.2 ...

    输入法示例程序

    This function creates a new input context, allocating memory for the context and initializing it. ImmCreateIMCC This function enables an IME to create a new input method context (IMC) component that...

    CUDA Reference from NVIDIA official site.

    `cudaThreadExit` is used to terminate the current CUDA context and release associated resources. It is important to call this function when no longer using a CUDA context to avoid resource leaks. ###...

    基于遗传算法的作业调度优化研究.docx

    The results demonstrate that the proposed algorithm yields satisfactory outcomes, efficiently allocating resources and enhancing production organization. The algorithm's performance is beneficial in ...

    Professional_Linux_Programming.pdf

    Configuring to the Local Environment 21 Building the Sources 22 Components of the GNU Toolchain 23 The GNU Compiler Collection 23 The GNU binutils 34 GNU Make 39 The GNU Debugger 40 02_776130 ftoc.qxp...

    Linux System Administrator Guide Version0.9

    The guide addresses the common debate between referring to the operating system as "Linux" versus "GNU/Linux." This distinction is important because the Linux kernel is just one component of the ...

    Professional.MFC.with.VC6

    Another Path to Type Safety Files CFile CStdioFile CMemFile MFC and File Security Sundry Stuff Wait Cursors Error Messages Summary Chapter 11: Writing Multithreaded Applications with MFC ...

    RadControls.for.ASP.NET2.Q1.2007.SP2.RadUpload.Net2.v2.3.2.0

    a Progress area control, designed to monitor file uploads or any other measurable process on the server. Browser Support Telerik RadUpload supports all major browsers and platforms (both on PC and Mac...

Global site tag (gtag.js) - Google Analytics