2017-07-24 151 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

相关问题