2017-07-24 148 views
0

嗨大家都希望你做得很好 我的應用程序有問題,我使用下面的代碼連接到某個地址(正如你在這裏看到它的本地地址)我的問題是當我關閉我的wamp服務器,或者例如,如果我的應用程序無法連接到我之前提供的地址,我的應用程序會在特定時間後停止,並且會給我一個錯誤。 我想知道如何更改我的代碼,當應用程序找不到地址(由於任何原因),我的應用程序給用戶的消息而不是Keep stops.how我可以處理嗎?httpURLConnection使我的應用程序停止

這裏是我的代碼

String json_url = "http://10.0.2.2/ss/1.php"; 
    @Override 
    protected String doInBackground(Void...voids){ 
     try{ 
      URL url = new URL(json_url); 
      HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection(); 
      httpURLConnection.connect(); 
      InputStream inputStream = httpURLConnection.getInputStream(); 
      BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream)); 
      StringBuilder stringBuilder = new StringBuilder(); 
      while((json_string=bufferedReader.readLine())!=null){ 
       stringBuilder.append(json_string+"\n"); 
      } 
      bufferedReader.close(); 
      inputStream.close(); 
      httpURLConnection.disconnect(); 
      return stringBuilder.toString().trim(); 
     } catch (MalformedURLException e){ 
      e.printStackTrace(); 
     } catch (IOException e){ 
      e.printStackTrace(); 
      System.out.println("Deal With Wrong Address"); 
      return null; 
     } 
     return null; 
    } 

感謝您的幫助。

+0

你有沒有下面的答案的幫助? –

回答

0

首先,您應該檢查您的應用程序是否具有Internet連接,然後只能調用此方法。

ConnectivityManager connMan = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); 
NetworkInfo netInfo = connMan.getActiveNetworkInfo(); 
if (netInfo != null && netInfo.isConnected()) { 
// Do stuff here for API call 
} 

一旦你叫,你可以使用進一步捕獲超時異常,並顯示自定義的味精在您嘗試捕捉

添加以下catch塊

 }catch (SocketTimeoutException bug) { 
      Toast.makeText(getApplicationContext(), "Socket Timeout", Toast.LENGTH_LONG).show(); 
     } catch (ConnectTimeoutException bug) { 
      Toast.makeText(getApplicationContext(), "Connection Timeout", Toast.LENGTH_LONG).show(); 
     } 

還設置ConnectionTimeout參數以及您的要求 -

httpURLConnection.setConnectTimeout(5000); // 5 sec timeout 
+0

感謝您的幫助,但它仍然沒有工作:( –

+0

@AmirAlizadehHesari現在有什麼問題嗎?你有任何錯誤 –

0

夥計們我想我已經修好了 所有我需要的是這條線

return String.valueOf(0); 

而不是

return null; 

但許多感謝kapsym

相關問題