如果URL无法访问或Internet不可用,则网络连接异常处理

时间:2014-06-04 12:26:36

标签: android

try{
  String out_url="http://algotips.com/";
  URL urlObject=new URL(out_url);
  conn = (HttpURLConnection) urlObject.openConnection();
  conn.setReadTimeout(100000);//milliseconds
  conn.setConnectTimeout(150000);//milliseconds
  conn.setRequestMethod("GET");
  conn.setDoInput(true);
}
catch(Exception e){ 
   /*Exception*/ 
}

我的应用程序因以下原因而崩溃:

  • 如果互联网连接不可用,则意味着设备未连接到WiFi或WiFi连接受限。
  • 如果无法访问该网站。

如何处理这些情况?

2 个答案:

答案 0 :(得分:0)

为了检查连接可用性,在调用以下方法之前,请使用ConnectivityManager检查连接可用性。如果不可用,请显示使用错误。

如果无法访问连接和URL /服务器,则以下解决方案将为您提供帮助!

对于使用post web-services,这是我们使用的代码: 如果响应为空,则可能是服务器问题,我们会相应地处理它。

private HttpResponse getWebServiceResponse(String URL, ArrayList <NameValuePair> params)
{
    HttpResponse httpResponse = null;
    try 
    {

        HttpParams httpParameters = new BasicHttpParams();

        // Set the timeout in milliseconds until a connection is established.
        // The default value is zero, that means the timeout is not used. 
        int timeoutConnection = 20000;
        HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);

        // Set the default socket timeout (SO_TIMEOUT) 
        // in milliseconds which is the timeout for waiting for data.
        int timeoutSocket = 20000;
        HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);              

        // defaultHttpClient
        DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters);
        httpClient.getCredentialsProvider().setCredentials(
                AuthScope.ANY, new UsernamePasswordCredentials(appProps.getProperty("USERNAME"), appProps.getProperty("PASSWORD")));    
        HttpPost httpPost = new HttpPost(URL);
        try 
        {
            httpPost.setEntity(new UrlEncodedFormEntity(params));
        } catch (UnsupportedEncodingException e) {

        }
        httpResponse = httpClient.execute(httpPost);
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }       
    return httpResponse;
}

对于Get Request,相应地更改(包括超时和套接字超时,如上例所示):

// For calling GET method
public static void callWebServiceGET (String URL, String userName, String password, ArrayList<NameValuePair> params)
{
    HttpClient httpclient = new DefaultHttpClient();

    HttpGet httpget;
    String querystring = URLEncodedUtils.format(params, "utf-8");
    URL = URL + "?" + querystring;
    log.info("URL to be consumed via GET request is --> " + URL);
    httpget = new HttpGet(URL);
    HttpResponse httpResponse = null; 
    try 
    {
        httpget.addHeader(BasicScheme.authenticate(
                new UsernamePasswordCredentials(userName, password),
                "UTF-8", false));

        httpResponse = httpclient.execute(httpget);

        HttpEntity entity = httpResponse.getEntity();

        String respstring = EntityUtils.toString(entity);


        if (entity != null)
        {
            entity.consumeContent();
        }

    } catch (Exception e) {
        log.error("Exception caught :: " +e);
        e.printStackTrace();
    }

} // End of method callWebServiceGET

答案 1 :(得分:0)

在尝试连接互联网之前,您必须先检查互联网。

private boolean isConnected(Context ctx){
ConnectivityManager connMgr = (ConnectivityManager)ctx.getSystemService(Activity.CONNECTIVITY_SERVICE);
            NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
            if (networkInfo != null && networkInfo.isConnected()) 
                return true;
            else
                return false;   
    }