Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8691231
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 13, 20262026-06-13T00:04:50+00:00 2026-06-13T00:04:50+00:00

I have application which connects to server via RestClient. And I want to implement

  • 0

I have application which connects to server via RestClient. And I want to implement right error handling approach there, specifically, ConnectException and HttpHostConnectException if user lost internet connection.
I implemented AsyncTask class in RestClient with all PUT,GET,POST,DELETE methods and handling the result there. And I want to throw my own exception, for example NoInternetConnection if user get exception matching above. And handle my own exception, reloading current Activity and showing message “No Internet” message.
I tried to handle HttpHostConnectException in RestClient and throw my NoInternetConnection and catch it in my Activity but I got

 Unreachable catch block for NoInternetException. This exception is never thrown from the try statement body

That’s mean that I should throw my exception from the try statement of Activity. I tried to use static variable of error and throw the exception from Activity if this variable is true from RestClient. But I don’t think it is the best approach.
One more thought was to hanle all the errors in RestClient class, but it is not an Activity and I should use Handler or somethink like that to determine the current Activity and show my Toast message of internet losing.
Tell me please what is the best approach.
My RestClient class:

  public class RestClient
   {
     class AsyncExecute extends AsyncTask<RequestMethod, InputStream, Object> 
    {
          protected InputStream doInBackground(RequestMethod... param) {
              HttpUriRequest request;
                HttpResponse httpResponse;
                DefaultHttpClient client = getNewHttpClient();
                InputStream instream = null;
                RestClient.this.AddHeader(CoreProtocolPNames.USER_AGENT, "Android-AEApp,ID=2435743");
                RestClient.this.AddHeader(ClientPNames.COOKIE_POLICY,  CookiePolicy.RFC_2109);
                RestClient.this.AddHeader("User-Agent",  "Android-AEApp,ID=2435743");
                RestClient.this.AddHeader("Accept",  "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"); 
                if (CookieStorage.getInstance().getArrayList().isEmpty())
                    CookieStorage.getInstance().getArrayList().add("PHPSESSID=lc89a2uu0rj6t2p219gc2cq4i2");
                RestClient.this.AddHeader("Cookie",  CookieStorage.getInstance().getArrayList().get(0).toString()); 
                switch(param[0]) {
                    case GET:
                    {
                        //add parameters
                        String combinedParams = "";
                        if(!params.isEmpty()){
                            combinedParams += "?";
                            for(NameValuePair p : params)
                            {
                                String paramString = null;
                                try {
                                    paramString = p.getName() + "=" + URLEncoder.encode(p.getValue(),"UTF-8");
                                } catch (UnsupportedEncodingException e) {
                                    // TODO Auto-generated catch block
                                    e.printStackTrace();
                                }
                                if(combinedParams.length() > 1)
                                {
                                    combinedParams  +=  "&" + paramString;
                                }
                                else
                                {
                                    combinedParams += paramString;
                                }
                            }
                        }

                         request = new HttpGet(url + combinedParams);

                        //add headers
                        for(NameValuePair h : headers)
                        {
                            request.addHeader(h.getName(), h.getValue());
                        }

                       // executeRequest(request, url);
                        break;
                    }
                    case POST:
                    {
                        request = new HttpPost(url);

                        //add headers
                        for(NameValuePair h : headers)
                        {
                            request.addHeader(h.getName(), h.getValue());
                        }

                        if(!params.isEmpty()){
                            try {
                                ((HttpEntityEnclosingRequestBase) request).setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
                            } catch (UnsupportedEncodingException e) {
                                // TODO Auto-generated catch block
                                e.printStackTrace();
                            }
                        }           
                        break;
                    }
                    case PUT:
                    {
                        request = new HttpPut(url);

                        //add headers
                        for(NameValuePair h : headers)
                        {
                            request.addHeader(h.getName(), h.getValue());
                        }

                        if(!params.isEmpty()){
                            try {
                                ((HttpEntityEnclosingRequestBase) request).setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
                            } catch (UnsupportedEncodingException e) {
                                // TODO Auto-generated catch block
                                e.printStackTrace();
                            }
                        }


                        break;
                    }
                    case DELETE:
                    {
                        request = new HttpDelete(url);

                        //add headers
                        for(NameValuePair h : headers)
                        {
                            request.addHeader(h.getName(), h.getValue());
                        }

                        if(!params.isEmpty()){
                            try {
                                ((HttpEntityEnclosingRequestBase) request).setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
                            } catch (UnsupportedEncodingException e) {
                                // TODO Auto-generated catch block
                                e.printStackTrace();
                            }
                        }

                        //executeRequest(request, url);
                        break;
                    }
                    default:
                        request = null;
                }

                try {
                    httpResponse = client.execute(request);
                    if (httpResponse.getLastHeader("Set-Cookie")!=null)
                    {
                        CookieStorage.getInstance().getArrayList().remove(0);
                        CookieStorage.getInstance().getArrayList().add(httpResponse.getLastHeader("Set-Cookie").getValue());
                    }
                    responseCode = httpResponse.getStatusLine().getStatusCode();
                    message = httpResponse.getStatusLine().getReasonPhrase();
                    Header[] headers = httpResponse.getAllHeaders();
                    for(Header head : headers)
                    {
                        Log.i("RestClient headers", head.toString());
                    }
                    Log.i("RestClient response status code", Integer.toString(responseCode));
                    if (responseCode == 401)
                    {

                        Intent i = new Intent(context,
                                LoginActivity.class);
                        i.putExtra("relogin", true);
                        i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        context.startActivity(i);

                    }

                    HttpEntity entity = httpResponse.getEntity();
                    if (entity != null) {

                        instream = entity.getContent();

                    }

                } catch (ClientProtocolException e)  {

                    client.getConnectionManager().shutdown();
                    e.printStackTrace();
                } 

                catch (IOException e) {
                    client.getConnectionManager().shutdown();
                    publishProgress();
                    e.printStackTrace();
                }

                return instream;

          }
          protected void onProgressUpdate(Void... progress) {
              Toast.makeText(context, "You've lost internet connection. You should try later.",Toast.LENGTH_LONG)
               .show();
            }

            protected void onPostExecute(Object  result) {

                 if(result instanceof Exception) {
                        try {
                            throw new NoInternetException();
                        } catch (NoInternetException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                    }
                    else{

                        super.onPostExecute((InputStream) result);
                        }
                    }

            }
    public InputStream Execute(RequestMethod method) throws Exception
    {   
        AsyncExecute mt = new AsyncExecute();
        mt.execute(method);
        InputStream stream  = (InputStream) mt.get();
        return stream;
     }
  }
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-13T00:04:51+00:00Added an answer on June 13, 2026 at 12:04 am

    I think that if you have errors (or success to report you should do it from RestClient – as you say you will need a way to address the UI thread using the standard handler techniques.

    Using a static singleton is generally considered an anti-pattern and is probably a bad idea.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have an application which uses connection to server via Wifi. When starting the
I have a PHP application which connects to Microsoft Exchange server to retrieve 'Contacts'
We have an application written in Delphi 2010 which connects to SQL Server Database.
I have an application which connects to SQL Server 2000 (using a generic SQL
I have an application server which connects to a database server. I would like
I have a WPF application which connects to a remote database over internet and
in my zf application i have base model class Application_Model, which connects to db
I created a desktop application in C#/WPF which connects to a SQL Server 2008
I have a C++ application which sends images to a Flex/Air front-end via TCP
I've got an application which does connect to a MySQL 5-Server via the ODBC-Driver.

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.