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

倖福魔咒の 提交于 2019-12-12 22:40:18

问题


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


回答1:


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.




回答2:


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?


来源:https://stackoverflow.com/questions/4205210/read-data-from-http-response-rarely-throws-bindexception-address-already-in-use

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!