遵循以下说明后会发生 java.net.UnknownHostException:
指示:
- 断开计算机与 Internet 的连接(例如:关闭调制解调器)
- 将操作系统日期更改为未来 14 天
- 运行下面的代码
- 单击“执行测试”按钮
- 您将收到一条异常消息,但这是正确的,因为互联网已断开连接
- 在消息窗口中单击确定
- 重新连接互联网
- 将操作系统日期更改回今天的日期
- 单击“执行测试”按钮
- 您将收到一条异常消息,但您不应该,因为互联网已连接
- 您可以一次又一次地单击“执行测试”按钮,尽管已连接到互联网,但总是会出现相同的异常。
- 如果您在浏览器上测试 URL ( http://test.com ),它将起作用
为什么会这样?我想这不应该发生。
简单代码:
公共类 TestUrlConnection{
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable(){
@Override
public void run(){
createAndShowGui();
}
});
}
private static void createAndShowGui(){
final JFrame frame = new JFrame("Test URL Connection");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JButton btOk = new JButton("Perform Test");
btOk.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent e){
try{
String content = readContentFromTestUrl();
if(content!=null)
JOptionPane.showMessageDialog(frame, "OK. URL Connection returned Content.\nContent length = "+content.length());
else
JOptionPane.showMessageDialog(frame, "Content is null, but no exception");
}
catch(IOException exc){
JOptionPane.showMessageDialog(frame, "Exception:\n\n"+stackTraceToString(exc));
}
}
});
frame.setContentPane(btOk);
frame.setMinimumSize(new Dimension(250,100));
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
private static String readContentFromTestUrl() throws IOException{
InputStream is = null;
InputStreamReader isr = null;
BufferedReader br = null;
try {
URL url = new URL("http://test.com");
URLConnection urlConnection = url.openConnection();
urlConnection.setUseCaches(false);
is = urlConnection.getInputStream();
isr = new InputStreamReader(is);
br = new BufferedReader(isr);
String inputLine;
String content = "";
while ((inputLine = br.readLine()) != null)
content += inputLine + "\n";
return content;
}
finally{
if(is!=null){try{is.close();}catch(IOException e){e.printStackTrace();}}
if(isr!=null){try{isr.close();}catch(IOException e){e.printStackTrace();}}
if(br!=null){try{br.close();}catch(IOException e){e.printStackTrace();}}
}
}
private static String stackTraceToString(IOException exc){
exc.printStackTrace();
StringWriter sw = new StringWriter();
exc.printStackTrace(new PrintWriter(sw));
String s = sw.toString();
return s.substring(0, s.length()>600 ? 600 : s.length());
}
}