我在 Tomcat 上运行一个 Web 应用程序。我的应用程序连接到其他 Web 服务来满足来自客户端的请求。有时我在打开 URL 连接时收到 java.net.UnknownHostException,然后有时我开始收到 java.net.SocketException: Too many open files。我的服务器停止进一步接受连接。请指导。
String response;
HttpURLConnection conn = null;
BufferedReader rd = null;
InputStream in = null;
try
{
// Send data
String urlStr = URL;
URL url = new URL(urlStr);
conn = (HttpURLConnection)url.openConnection();
conn.setRequestProperty("content-type", "application/x-www-form-urlencoded");
int contentLength = conn.getContentLength();
// System.out.println("content length 1" + contentLength);
if (contentLength <= 0)
{
InputStream in1 = (conn).getErrorStream();
if (in1 != null)
{
in1.close();
}
conn.getInputStream().close();
in = null;
conn.disconnect();
conn = null;
return null;
}
in = conn.getInputStream();
if (conn.getResponseCode() != 200)
{
InputStream in1 = (conn).getErrorStream();
if (in1 != null)
{
in1.close();
}
conn.getInputStream().close();
in = null;
conn.disconnect();
conn = null;
in.close();
in = null;
return null;
}
// Get the response
rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuffer stringBuffer = new StringBuffer();
String line = null;
while ((line = rd.readLine()) != null)
{
stringBuffer.append(line);
}
response = stringBuffer.toString();
System.out.println("full ads response = " + response);
}
catch (Exception ex)
{
// ex.printStackTrace();
}
finally
{
try
{
if (conn != null)
{
InputStream in1 = (conn).getErrorStream();
if (in1 != null)
{
in1.close();
}
conn.getInputStream().close();
in = null;
conn.disconnect();
conn = null;
}
if (rd != null)
{
rd.close();
rd = null;
}
if (in != null)
{
in.close();
in = null;
}
}
catch (Exception e)
{
}
}
return null;