`

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 ...

    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 ...

    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. ...

    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...

    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...

    On Allocating Cache Resources to Content Providers

    On Allocating Cache Resources to Content Providers

    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...

    DB2pureScale_Practical_Design_Guide_2016-Feb-5.pptx

    3-2 Allocating a portion of the LBP size to LOCKLIST 3-3 Avoid lock escalation with GLM Size 3-4 PAGE_AGE_TRGT_GCR – Improve Performance but also Increases Recovery time 3-5 Setting the correct ...

    Programming in Lua 4th.pdf

    Automatic memory management simplifies interfaces, because there is no need to decide who is responsible for allocating and deallocating memory or how to handle overflows. First-class functions allow...

    The Art of Leaks: The Return of Heap Feng Shui

    Using the vulnerability of allocating the large heap without randomness, we can leak any object address allocated in jscript9 custom heap, and bypass ASLR in Internet Explorer on Windows 7/8/8.1.

    Transmission Sequence Design and Allocation for Wide Area Ad Hoc Networks

    In this paper we examine the question of designing and allocating transmission sequences to users in a mobile ad hoc network that has no spatially boundary. A basic tenet of the transmission sequence ...

    understanding linux network internals

    He shows the purposes of major networking features and the trade-offs involved inchoosing one solution over another. A large number of flowcharts and other diagrams enhance the book's ...

    TMS320x28xx PWM module

    The ePWM unit described here addresses these requirements by allocating all needed timing and control resources on a per PWM channel basis. Cross coupling or sharing of resources has been avoided; ...

    Essential Linux Device Drivers

    Talking to the Parallel Port RTC Subsystem Pseudo Char Drivers Misc Drivers Character Caveats Looking at the Sources Chapter 6. Serial Drivers Layered Architecture UART Drivers TTY Drivers ...

Global site tag (gtag.js) - Google Analytics