A java.net.UnknownHostException occurs after following the instructions below:
Instructions:
- Disconnect the computer from the Internet (eg: turning off the modem)
- Change the OS date to 14 days in the future
- Run the code below
- Click the "Perform test" button
- You will get an exception message, but that's right, because the internet is disconnected
- Click OK in the message window
- Reconnect the internet
- Change the OS date back to today's date
- Click the "Perform test" button
- You will get an exception message, but you shouldn't, because the internet is connected
- You can click the "Perform test" button again and again, getting always the same exception, despite being connected to internet.
- If you test the the URL (http://test.com) at browser it will work
Why does this happen? I imagine that should not happen.
Simple Code:
public class 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());
}
}