PC
超时机制主要有:1、HTTP请求超时机制,2、Socket通信超时机制,HTTP请求超时机制,public static void main(String[] args){long a=System.currentTimeMillis();try{URL myurl = new URL(“http://www.baidu.cn”); URLConnection myurlcon = myurl.openConnection();myurlcon.setConnectTimeout(1000);myurlcon.setReadTimeout(1000);
BufferedReader in = new BufferedReader(new InputStreamReader(myurlcon.getInputStream(),”UTF-8″));String inputLine;while ((inputLine = in.readLine()) != null){System.out.println(inputLine);in.close();
System.out.println(System.currentTimeMillis()-a);}} catch (MalformedURLException e) {e.printStackTrace();} catch (UnsupportedEncodingException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}}
如果超时将抛出以下异常:java.net.SocketTimeoutException: Read timed out.at java.net.SocketInputStream.socketRead0(Native Method)at java.net.SocketInputStream.read(SocketInputStream.java:129)at java.io.BufferedInputStream.fill(BufferedInputStream.java:218)at java.io.BufferedInputStream.read1(BufferedInputStream.java:256)。
at java.io.BufferedInputStream.read(BufferedInputStream.java:313)at sun.net.www.http.HttpClient.parseHTTPHeader(HttpClient.java:606)at sun.net.www.http.HttpClient.parseHTTP(HttpClient.java:554)at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:940)at com.Test.main(Test.java:52)。
网络虽好,但要注意劳逸结合哦!
如果是青少年,小编在这里提示大家千万不能沉迷网络!