2012-05-24 50 views
0

由於某種原因,當我發出GET請求時,它似乎進入無限循環。我認爲這是我的網絡應用程序有問題,但在嘗試google.com之後,會發生相同的結果。android http請求無限循環

try { 
     URL url = new URL("http://google.com"); 

     HttpURLConnection con = (HttpURLConnection) url.openConnection(); 
     con.setReadTimeout(10000 /* milliseconds */); 
     con.setConnectTimeout(15000 /* milliseconds */); 
     con.setRequestMethod("GET"); 
     con.setDoInput(true); 
     con.connect(); 

     InputStream is = con.getInputStream(); 
     BufferedReader reader = new BufferedReader(new InputStreamReader(is)); 

     for (String line = reader.readLine(); line != null;) { 
      System.out.println(line); 
     } 
     reader.close(); 

    } catch (ClientProtocolException e) { 
     System.out.println("Client Exception " + e.getMessage()); 
    } catch(IOException e) { 
     e.printStackTrace(); 
     System.out.println("IOException " + e.getMessage()); 
    } 

此代碼從未通過for循環。它只是繼續打印。任何人看到有什麼問題?

+0

顯然它是for循環的條件。嘗試使用while循環,這使得它更簡單。這裏是一個有用的鏈接http://stackoverflow.com/questions/2500107/how-should-i-read-from-a-buffered-reader – shawndreck

回答

1

線= reader.readLine()調用shuold每次當循環運行,但在你的代碼中只有一次,因爲它是初始化部分的零件批量..

enter image description here

嘗試somehhing像

for (; (line =reader.readLine()) != null;) { 

    } 

or 


    while ((line = br.readLine()) != null) {} 
+0

當然,我其實是爲了寫(String line;(line = reader .readLine())!= null;)謝謝! – user1218776

1

的問題是在這裏

for (String line = reader.readLine(); line != null;) { 
    System.out.println(line); 
} 

「線」始終是輸入的第一道防線。你需要閱讀新的行。