Android开发教程:HTTP超时机制


由于手机端应用的响应,与当时的无线通信网络状况有很大的关联。而通信网络往往具有不稳定,延迟长的特点。所以,在我们的应用程序中,当我们请求网络的时候,超时机制的应用就显得特别重要。

超时机制主要有:

1、HTTP请求超时机制

2、Socket通信超时机制

HTTP请求超时机制

  1. public static void main(String[] args){   
  2.   
  3. long a=System.currentTimeMillis();   
  4. try{   
  5. URL myurl = new URL(“http://www.bkjia.com”);   
  6. URLConnection myurlcon = myurl.openConnection();   
  7. myurlcon.setConnectTimeout(1000);   
  8. myurlcon.setReadTimeout(1000);   
  9. BufferedReader in = new BufferedReader(new InputStreamReader(myurlcon.getInputStream(),”UTF-8″));   
  10. String inputLine;   
  11.   
  12. while ((inputLine = in.readLine()) != null){   
  13. System.out.println(inputLine);   
  14. in.close();   
  15. System.out.println(System.currentTimeMillis()-a);   
  16. }   
  17. catch (MalformedURLException e) {   
  18. e.printStackTrace();   
  19. catch (UnsupportedEncodingException e) {   
  20. e.printStackTrace();   
  21. catch (IOException e) {   
  22. e.printStackTrace();   
  23. }   
  24.   
  25. }   
  26.   
  27.   
  28. 如果超时 将 抛出 以下 异常   
  29.   
  30. java.net.SocketTimeoutException: Read timed out   
  31. at java.net.SocketInputStream.socketRead0(Native Method)   
  32. at java.net.SocketInputStream.read(SocketInputStream.java:129)   
  33. at java.io.BufferedInputStream.fill(BufferedInputStream.java:218)   
  34. at java.io.BufferedInputStream.read1(BufferedInputStream.java:256)   
  35. at java.io.BufferedInputStream.read(BufferedInputStream.java:313)   
  36. at sun.net.www.http.HttpClient.parseHTTPHeader(HttpClient.java:606)   
  37. at sun.net.www.http.HttpClient.parseHTTP(HttpClient.java:554)   
  38. at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:940)   
  39. at com.Test.main(Test.java:52)  
  • 1
  • 2
  • 3
  • 下一页

相关内容