由於手機端應用的響應,與當時的無線通信網絡狀況有很大的關聯。而通信網絡往往具有不穩定,延遲長的特點。所以,在我們的應用程序中,當我們請求網絡的時候,超時機制的應用就顯得特別重要。
超時機制主要有:
1、HTTP請求超時機制
2、Socket通信超時機制
HTTP請求超時機制
- public static void main(String[] args){
-
- long a=System.currentTimeMillis();
- try{
- URL myurl = new URL(“http://www.linuxidc.com”);
- 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)