Android开发教程:HTTP超时机制
Android开发教程:HTTP超时机制
由于手机端应用的响应,与当时的无线通信网络状况有很大的关联。而通信网络往往具有不稳定,延迟长的特点。所以,在我们的应用程序中,当我们请求网络的时候,超时机制的应用就显得特别重要。
超时机制主要有:
1、HTTP请求超时机制
2、Socket通信超时机制
HTTP请求超时机制
- public static void main(String[] args){
- long a=System.currentTimeMillis();
- try{
- URL myurl = new URL(“http://www.bkjia.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)
|
评论暂时关闭