我有通过 RestClient 连接到服务器的应用程序。我想在那里实施正确的错误处理方法,特别是如果用户失去互联网连接,则使用 ConnectException 和 HttpHostConnectException。我在 RestClient 中实现了 AsyncTask 类,其中包含所有 PUT、GET、POST、DELETE 方法并在那里处理结果。如果用户在上面得到异常匹配,我想抛出我自己的异常,例如 NoInternetConnection。并处理我自己的异常,重新加载当前 Activity 并显示消息“No Internet”消息。我试图在 RestClient 中处理 HttpHostConnectException 并抛出我的 NoInternetConnection 并在我的 Activity 中捕获它,但我得到了
Unreachable catch block for NoInternetException. This exception is never thrown from the try statement body
这意味着我应该从 Activity 的 try 语句中抛出我的异常。我尝试使用错误的静态变量,如果此变量在 RestClient 中为真,则从 Activity 中抛出异常。但我认为这不是最好的方法。另一个想法是处理 RestClient 类中的所有错误,但它不是 Activity,我应该使用 Handler 或类似的方法来确定当前的 Activity 并显示我的 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;
}
}