0

RestClient経由でサーバーに接続するアプリケーションがあります。そして、そこで正しいエラー処理アプローチを実装したいと思います。具体的には、ユーザーがインターネット接続を失った場合のConnectExceptionとHttpHostConnectExceptionです。すべてのPUT、GET、POST、DELETEメソッドを使用してRestClientにAsyncTaskクラスを実装し、そこで結果を処理しました。そして、ユーザーが上記の例外一致を取得した場合、たとえばNoInternetConnectionなどの独自の例外をスローしたいと思います。そして、私自身の例外を処理し、現在のアクティビティをリロードして、「インターネットがありません」というメッセージを表示します。RestClientでHttpHostConnectExceptionを処理し、NoInternetConnectionをスローして、アクティビティでキャッチしようとしましたが、

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

つまり、Activityのtryステートメントから例外をスローする必要があります。エラーの静的変数を使用して、この変数がRestClientからtrueの場合、Activityから例外をスローしようとしました。しかし、それが最善のアプローチではないと思います。もう1つの考えは、RestClientクラスのすべてのエラーを処理することでしたが、これはアクティビティではないため、ハンドラーなどを使用して現在のアクティビティを判別し、インターネットが失われたというToastメッセージを表示する必要があります。最善のアプローチを教えてください。私のRestClientクラス:

  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;
     }
  }
4

1 に答える 1

0

エラーが発生した場合 (または報告に成功した場合は、RestClient から実行する必要があると思います。標準のハンドラー手法を使用して UI スレッドに対処する方法が必要になると言われています。

静的なシングルトンを使用することは、一般的にアンチパターンと見なされ、おそらく悪い考えです。

于 2012-10-16T11:22:23.580 に答える