开发者

Read Data From Http Response rarely throws BindException: Address already in use

I use following code to read data form http request. In general cases it works good, but some time "httpURLConnection.getResponseCode()" throws java.net.BindException: Address already in use: connect

     ............
     URL url = new URL( strUrl );
     httpURLConnection = (HttpURLConnection)url.openConnection();
     int responseCode = httpURLConn开发者_高级运维ection.getResponseCode();
     char charData[] = new char[HTTP_READ_BLOCK_SIZE];
     isrData = new InputStreamReader( httpURLConnection.getInputStream(), strCharset );
     int iSize = isrData.read( charData, 0, HTTP_READ_BLOCK_SIZE );
     while( iSize > 0 ){
            sbData.append( charData, 0, iSize );
            iSize = isrData.read( charData, 0, HTTP_READ_BLOCK_SIZE );
     }
     .................





 finally{
            try{
                if( null != isrData ){
                    isrData.close();
                    isrData = null;
                }

                if( null != httpURLConnection ){
                    httpURLConnection.disconnect();
                    httpURLConnection = null;
                }

                strData = sbData.toString();
             }
            catch( Exception e2 ){
            }

The code running on Java 1.6, Tomcat 6. Thank you


Get rid of the disconnect() and close the Reader instead. You are running out of local ports, and using disconnect() disables HTTP connection pooling which is the solution to that.


You need to close() the Reader after completely reading the stream. This will free up underlying resources (sockets, etc) for future reuse. Otherwise the system will run out of resources.

The basic Java IO idiom for your case is the following:

Reader reader = null;
try {
    reader = new InputStreamReader(connection.getInputStream(), charset);
    // ...
} finally {
    if (reader != null) try { reader.close(); } catch (IOException logOrIgnore) {}
}

See also:

  • Java IO tutorial
  • How to use URLConnection?
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜