代码之家  ›  专栏  ›  技术社区  ›  Boris

从Http响应读取数据很少抛出BindException:Address已经在使用

  •  1
  • Boris  · 技术社区  · 15 年前

    我使用以下代码从http请求中读取数据。 一般情况下,它运行良好,但有时“httpURLConnection.getResponseCode()”抛出java.net.BindException:Address已经在使用: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 ){
                }
    

    运行在Java1.6、Tomcat6上的代码。 谢谢你

    2 回复  |  直到 15 年前
        1
  •  2
  •   user207421    15 年前

    去掉disconnect()并关闭读卡器。您的本地端口即将用完,使用disconnect()将禁用HTTP连接池,这是解决此问题的方法。

        2
  •  1
  •   Community Mohan Dere    9 年前

    你需要 close() 这个 Reader 完全读了这条小溪之后。这将释放底层资源(套接字等)以供将来重用。否则系统将耗尽资源。

    您的案例的基本Java IO习惯用法如下:

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

    另见: