2016-12-16 90 views
0

我打電話給服務器任務,我想捕獲所有與網絡相關的異常。我得到java.net.ConnectException。我沒有從哪裏投射,哪裏可以抓到。如何捕獲ConnectionException,UnknownHostException?

服務器類:

public class ServerRequest { 
    String api; 
    JSONObject jsonParams; 

    public ServerRequest(String api, JSONObject jsonParams) { 
     this.api = api; 
     this.jsonParams = jsonParams; 
    } 

    public JSONObject sendRequest(){ 
     try { 
      URL url = new URL(api); 
      HttpURLConnection con = (HttpURLConnection)url.openConnection(); 
      con.setRequestMethod("POST"); 
      con.setRequestProperty("Content-Type", "application/json"); 
      con.setDoOutput(true); 
      con.setDoInput(true); 
      OutputStreamWriter writer = new OutputStreamWriter(con.getOutputStream()); 
      writer.write(jsonParams.toString()); 
      writer.close(); 

      int responseCode = con.getResponseCode(); 
      if (responseCode == HttpURLConnection.HTTP_OK) { 
       StringBuilder sb = new StringBuilder(); 
       BufferedReader reader = new BufferedReader(new InputStreamReader(con.getInputStream())); 
       String line = ""; 
       while ((line = reader.readLine()) != null){ 
        sb.append(line); 
       } 
       reader.close(); 
       Log.d("ServerResponse", new String(sb)); 
       return new JSONObject(new String(sb)); 
      } else { 
       throw new UnexpectedServerException("Unexpected server exception with status code : "+responseCode); 
      } 
     } catch (MalformedURLException me) { 
      me.printStackTrace(); 
      return Excpetion2JSON.getJSON(me); 
     } catch(IOException ioe) { 
      ioe.printStackTrace(); 
      return Excpetion2JSON.getJSON(ioe); 
     } catch(UnexpectedServerException ue) { 
      ue.printStackTrace(); 
      return Excpetion2JSON.getJSON(ue); 
     } catch (JSONException je) { 
      je.printStackTrace(); 
      return Excpetion2JSON.getJSON(je); 
     } 

    } 

    public ServerRequest(String api) { 
     this.api = api; 
    } 


    public JSONObject sendGetRequest() { 
     try { 
      URL url = new URL(api); 
      HttpURLConnection con = (HttpURLConnection)url.openConnection(); 
      con.setRequestMethod("GET"); 
      con.setDoInput(true); 

      int responseCode = con.getResponseCode(); 
      if (responseCode == HttpURLConnection.HTTP_OK) { 
       StringBuilder sb = new StringBuilder(); 
       BufferedReader reader = new BufferedReader(new InputStreamReader(con.getInputStream())); 
       String line = ""; 
       while ((line = reader.readLine()) != null){ 
        sb.append(line); 
       } 
       reader.close(); 
       Log.d("ServerResponse", new String(sb)); 
       return new JSONObject(new String(sb)); 
      } else { 
       throw new UnexpectedServerException("Unexpected server exception with status code : "+responseCode); 
      } 
     } catch (MalformedURLException me) { 
      me.printStackTrace(); 
      return Excpetion2JSON.getJSON(me); 
     } catch(IOException ioe) { 
      ioe.printStackTrace(); 
      return Excpetion2JSON.getJSON(ioe); 
     } catch(UnexpectedServerException ue) { 
      ue.printStackTrace(); 
      return Excpetion2JSON.getJSON(ue); 
     } catch (JSONException je) { 
      je.printStackTrace(); 
      return Excpetion2JSON.getJSON(je); 
     } 
    } 
} 

和異常是這些:

java.net.ConnectException: failed to connect to xesoftwares.co.in/104.131.162.126 (port 80): connect failed: ENETUNREACH (Network is unreachable) 
12-16 16:08:17.811 10957-11559/com.weberz W/System.err:  at libcore.io.IoBridge.connect(IoBridge.java:124) 
12-16 16:08:17.811 10957-11559/com.weberz W/System.err:  at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:200) 
12-16 16:08:17.811 10957-11559/com.weberz W/System.err:  at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:504) 
12-16 16:08:17.811 10957-11559/com.weberz W/System.err:  at java.net.Socket.connect(Socket.java:884) 
12-16 16:08:17.811 10957-11559/com.weberz W/System.err:  at com.android.okhttp.internal.Platform.connectSocket(Platform.java:117) 
12-16 16:08:17.811 10957-11559/com.weberz W/System.err:  at com.android.okhttp.internal.http.SocketConnector.connectRawSocket(SocketConnector.java:160) 
12-16 16:08:17.811 10957-11559/com.weberz W/System.err:  at com.android.okhttp.internal.http.SocketConnector.connectCleartext(SocketConnector.java:67) 
12-16 16:08:17.811 10957-11559/com.weberz W/System.err:  at com.android.okhttp.Connection.connect(Connection.java:152) 
12-16 16:08:17.811 10957-11559/com.weberz W/System.err:  at com.android.okhttp.Connection.connectAndSetOwner(Connection.java:185) 
12-16 16:08:17.811 10957-11559/com.weberz W/System.err:  at com.android.okhttp.OkHttpClient$1.connectAndSetOwner(OkHttpClient.java:128) 
12-16 16:08:17.811 10957-11559/com.weberz W/System.err:  at com.android.okhttp.internal.http.HttpEngine.nextConnection(HttpEngine.java:341) 
12-16 16:08:17.811 10957-11559/com.weberz W/System.err:  at com.android.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:330) 
12-16 16:08:17.811 10957-11559/com.weberz W/System.err:  at com.android.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:248) 
12-16 16:08:17.811 10957-11559/com.weberz W/System.err:  at com.android.okhttp.internal.huc.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:437) 
12-16 16:08:17.811 10957-11559/com.weberz W/System.err:  at com.android.okhttp.internal.huc.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:114) 
12-16 16:08:17.811 10957-11559/com.weberz W/System.err:  at com.android.okhttp.internal.huc.HttpURLConnectionImpl.getOutputStream(HttpURLConnectionImpl.java:245) 
12-16 16:08:17.811 10957-11559/com.weberz W/System.err:  at com.weberz.helper.ServerRequest.sendRequest(ServerRequest.java:37) 
12-16 16:08:17.811 10957-11559/com.weberz W/System.err:  at com.weberz.AsyncTasks.UpdateTokenAsyncTask.doInBackground(UpdateTokenAsyncTask.java:44) 
12-16 16:08:17.811 10957-11559/com.weberz W/System.err:  at com.weberz.AsyncTasks.UpdateTokenAsyncTask.doInBackground(UpdateTokenAsyncTask.java:17) 
12-16 16:08:17.811 10957-11559/com.weberz W/System.err:  at android.os.AsyncTask$2.call(AsyncTask.java:295) 
12-16 16:08:17.812 10957-11559/com.weberz W/System.err:  at java.util.concurrent.FutureTask.run(FutureTask.java:237) 
12-16 16:08:17.812 10957-11559/com.weberz W/System.err:  at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:234) 
12-16 16:08:17.812 10957-11559/com.weberz W/System.err:  at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113) 
12-16 16:08:17.812 10957-11559/com.weberz W/System.err:  at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588) 
12-16 16:08:17.812 10957-11559/com.weberz W/System.err:  at java.lang.Thread.run(Thread.java:818) 
12-16 16:08:17.812 10957-11559/com.weberz W/System.err: Caused by: android.system.ErrnoException: connect failed: ENETUNREACH (Network is unreachable) 
12-16 16:08:17.812 10957-11559/com.weberz W/System.err:  at libcore.io.Posix.connect(Native Method) 
12-16 16:08:17.817 10957-11559/com.weberz W/System.err:  at libcore.io.BlockGuardOs.connect(BlockGuardOs.java:111) 
12-16 16:08:17.817 10957-11559/com.weberz W/System.err:  at libcore.io.IoBridge.connectErrno(IoBridge.java:137) 
12-16 16:08:17.817 10957-11559/com.weberz W/System.err:  at libcore.io.IoBridge.connect(IoBridge.java:122) 
12-16 16:08:17.817 10957-11559/com.weberz W/System.err:  ... 24 more 
12-16 16:08:17.822 10957-11559/com.weberz W/System.err: java.net.ConnectException: failed to connect to xesoftwares.co.in/104.131.162.126 (port 80): connect failed: ENETUNREACH (Network is unreachable) 
12-16 16:08:17.822 10957-11559/com.weberz W/System.err:  at libcore.io.IoBridge.connect(IoBridge.java:124) 
12-16 16:08:17.822 10957-11559/com.weberz W/System.err:  at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:200) 
12-16 16:08:17.822 10957-11559/com.weberz W/System.err:  at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:504) 
12-16 16:08:17.822 10957-11559/com.weberz W/System.err:  at java.net.Socket.connect(Socket.java:884) 
12-16 16:08:17.822 10957-11559/com.weberz W/System.err:  at com.android.okhttp.internal.Platform.connectSocket(Platform.java:117) 
12-16 16:08:17.823 10957-11559/com.weberz W/System.err:  at com.android.okhttp.internal.http.SocketConnector.connectRawSocket(SocketConnector.java:160) 
12-16 16:08:17.823 10957-11559/com.weberz W/System.err:  at com.android.okhttp.internal.http.SocketConnector.connectCleartext(SocketConnector.java:67) 
12-16 16:08:17.823 10957-11559/com.weberz W/System.err:  at com.android.okhttp.Connection.connect(Connection.java:152) 
12-16 16:08:17.823 10957-11559/com.weberz W/System.err:  at com.android.okhttp.Connection.connectAndSetOwner(Connection.java:185) 
12-16 16:08:17.823 10957-11559/com.weberz W/System.err:  at com.android.okhttp.OkHttpClient$1.connectAndSetOwner(OkHttpClient.java:128) 
12-16 16:08:17.823 10957-11559/com.weberz W/System.err:  at com.android.okhttp.internal.http.HttpEngine.nextConnection(HttpEngine.java:341) 
12-16 16:08:17.823 10957-11559/com.weberz W/System.err:  at com.android.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:330) 
12-16 16:08:17.823 10957-11559/com.weberz W/System.err:  at com.android.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:248) 
12-16 16:08:17.823 10957-11559/com.weberz W/System.err:  at com.android.okhttp.internal.huc.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:437) 
12-16 16:08:17.823 10957-11559/com.weberz W/System.err:  at com.android.okhttp.internal.huc.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:114) 
12-16 16:08:17.823 10957-11559/com.weberz W/System.err:  at com.android.okhttp.internal.huc.HttpURLConnectionImpl.getOutputStream(HttpURLConnectionImpl.java:245) 
12-16 16:08:17.823 10957-11559/com.weberz W/System.err:  at com.weberz.helper.ServerRequest.sendRequest(ServerRequest.java:37) 
12-16 16:08:17.823 10957-11559/com.weberz W/System.err:  at com.weberz.Activities.MainActivity$GetUserAsyncTask.doInBackground(MainActivity.java:658) 
12-16 16:08:17.823 10957-11559/com.weberz W/System.err:  at com.weberz.Activities.MainActivity$GetUserAsyncTask.doInBackground(MainActivity.java:622) 
12-16 16:08:17.823 10957-11559/com.weberz W/System.err:  at android.os.AsyncTask$2.call(AsyncTask.java:295) 
12-16 16:08:17.823 10957-11559/com.weberz W/System.err:  at java.util.concurrent.FutureTask.run(FutureTask.java:237) 
12-16 16:08:17.823 10957-11559/com.weberz W/System.err:  at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:234) 
12-16 16:08:17.823 10957-11559/com.weberz W/System.err:  at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113) 
12-16 16:08:17.823 10957-11559/com.weberz W/System.err:  at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588) 
12-16 16:08:17.823 10957-11559/com.weberz W/System.err:  at java.lang.Thread.run(Thread.java:818) 
12-16 16:08:17.824 10957-11559/com.weberz W/System.err: Caused by: android.system.ErrnoException: connect failed: ENETUNREACH (Network is unreachable) 
12-16 16:08:17.825 10957-11559/com.weberz W/System.err:  at libcore.io.Posix.connect(Native Method) 
12-16 16:08:17.825 10957-11559/com.weberz W/System.err:  at libcore.io.BlockGuardOs.connect(BlockGuardOs.java:111) 
12-16 16:08:17.825 10957-11559/com.weberz W/System.err:  at libcore.io.IoBridge.connectErrno(IoBridge.java:137) 
12-16 16:08:17.825 10957-11559/com.weberz W/System.err:  at libcore.io.IoBridge.connect(IoBridge.java:122) 
12-16 16:08:17.825 10957-11559/com.weberz W/System.err:  ... 24 more 
12-16 16:08:17.831 10957-11559/com.weberz W/System.err: java.net.UnknownHostException: Unable to resolve host "xesoftwares.co.in": No address associated with hostname 
12-16 16:08:17.832 10957-11559/com.weberz W/System.err:  at java.net.InetAddress.lookupHostByName(InetAddress.java:470) 
12-16 16:08:17.832 10957-11559/com.weberz W/System.err:  at java.net.InetAddress.getAllByNameImpl(InetAddress.java:252) 
12-16 16:08:17.832 10957-11559/com.weberz W/System.err:  at java.net.InetAddress.getAllByName(InetAddress.java:215) 
12-16 16:08:17.832 10957-11559/com.weberz W/System.err:  at com.android.okhttp.internal.Network$1.resolveInetAddresses(Network.java:29) 
12-16 16:08:17.832 10957-11559/com.weberz W/System.err:  at com.android.okhttp.internal.http.RouteSelector.resetNextInetSocketAddress(RouteSelector.java:188) 
12-16 16:08:17.832 10957-11559/com.weberz W/System.err:  at com.android.okhttp.internal.http.RouteSelector.nextProxy(RouteSelector.java:157) 
12-16 16:08:17.832 10957-11559/com.weberz W/System.err:  at com.android.okhttp.internal.http.RouteSelector.next(RouteSelector.java:100) 
12-16 16:08:17.832 10957-11559/com.weberz W/System.err:  at com.android.okhttp.internal.http.HttpEngine.createNextConnection(HttpEngine.java:357) 
12-16 16:08:17.832 10957-11559/com.weberz W/System.err:  at com.android.okhttp.internal.http.HttpEngine.nextConnection(HttpEngine.java:340) 
12-16 16:08:17.832 10957-11559/com.weberz W/System.err:  at com.android.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:330) 
12-16 16:08:17.832 10957-11559/com.weberz W/System.err:  at com.android.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:248) 
12-16 16:08:17.833 10957-11559/com.weberz W/System.err:  at com.android.okhttp.internal.huc.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:437) 
12-16 16:08:17.833 10957-11559/com.weberz W/System.err:  at com.android.okhttp.internal.huc.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:114) 
12-16 16:08:17.833 10957-11559/com.weberz W/System.err:  at com.android.okhttp.internal.huc.HttpURLConnectionImpl.getOutputStream(HttpURLConnectionImpl.java:245) 
12-16 16:08:17.833 10957-11559/com.weberz W/System.err:  at com.weberz.helper.ServerRequest.sendRequest(ServerRequest.java:37) 
12-16 16:08:17.833 10957-11559/com.weberz W/System.err:  at com.weberz.AsyncTasks.GetContactsAsyncTask.doInBackground(GetContactsAsyncTask.java:90) 
12-16 16:08:17.833 10957-11559/com.weberz W/System.err:  at com.weberz.AsyncTasks.GetContactsAsyncTask.doInBackground(GetContactsAsyncTask.java:32) 
12-16 16:08:17.833 10957-11559/com.weberz W/System.err:  at android.os.AsyncTask$2.call(AsyncTask.java:295) 
12-16 16:08:17.833 10957-11559/com.weberz W/System.err:  at java.util.concurrent.FutureTask.run(FutureTask.java:237) 
12-16 16:08:17.833 10957-11559/com.weberz W/System.err:  at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:234) 
12-16 16:08:17.833 10957-11559/com.weberz W/System.err:  at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113) 
12-16 16:08:17.833 10957-11559/com.weberz W/System.err:  at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588) 
12-16 16:08:17.833 10957-11559/com.weberz W/System.err:  at java.lang.Thread.run(Thread.java:818) 
12-16 16:08:17.833 10957-11559/com.weberz W/System.err: Caused by: android.system.GaiException: android_getaddrinfo failed: EAI_NODATA (No address associated with hostname) 
12-16 16:08:17.833 10957-11559/com.weberz W/System.err:  at libcore.io.Posix.android_getaddrinfo(Native Method) 
12-16 16:08:17.833 10957-11559/com.weberz W/System.err:  at libcore.io.ForwardingOs.android_getaddrinfo(ForwardingOs.java:55) 
12-16 16:08:17.833 10957-11559/com.weberz W/System.err:  at java.net.InetAddress.lookupHostByName(InetAddress.java:451) 
12-16 16:08:17.834 10957-11559/com.weberz W/System.err:  ... 22 more 

我怎能趕上UnknownHostExceptionjava.net.ConnectionExceptionUnexpectedServerExceptionMalformedServerException所有這些異常?

我試過JSONException後趕上postExecute方法例外,但它顯示的異常沒有拋出這裏..

請幫助。謝謝..

編輯:我試過這樣的事情,添加一個布爾變量,並使其當真例外拋出,但不工作..請檢查;

public class GetContactsAsyncTask extends AsyncTask<String, Void, JSONObject> { 
    String api; 
    String userId; 
    JSONObject jsonParams; 
    private ArrayList<Contact> contactList = new ArrayList<Contact>(); 
    public JSONArray contactListArray; 
    private RecyclerView recyclerView; 
    ContactGetCallBack contactGetCallBack; 
    private ContactAdapter adapter; 
    private static String KEY_SUCCESS1 = "Success"; 
    private Context mContext; 
    private ProgressDialog progressDialog; 
    private MainActivity activity; 
    private ContactTableHelper contactDb; 
    private Boolean exception = false; 

    public GetContactsAsyncTask(ContactGetCallBack contactGetCallBack, Context context, String userId,MainActivity activity) { 
     this.mContext = context; 
     this.userId = userId; 
     this.contactGetCallBack=contactGetCallBack; 
     this.progressDialog = new ProgressDialog(mContext); 
     this.activity = activity; 
    } 
    public interface ContactGetCallBack { 
     void doPostExecute(ArrayList<Contact> contactArrayList) throws JSONException; 
    } 

    @Override 
    protected void onPreExecute() { 

     super.onPreExecute(); 

     if(!isOnline()) 
     { 
      activity.showAlert("Please check internet connection."); 
     } 
     else { 

      // progressDialog=new ProgressDialog(mContext); 
      progressDialog.setMessage("Please wait..."); 
      progressDialog.setIndeterminate(false); 
      progressDialog.setCancelable(false); 
      progressDialog.show(); 
     } 
    } 



    @Override 
    protected JSONObject doInBackground(String...params) { 
     try { 
      api = ServiceUrl.getBaseUrl() + ServiceUrl.getContactsUrl();; 
      jsonParams = new JSONObject(); 

      String user_id = this.userId; 

      jsonParams.put("user_id", user_id); // params[0] is userid 

      ServerRequest request = new ServerRequest(api, jsonParams); 
      return request.sendRequest(); 

     } catch (JSONException je) { 
      return Excpetion2JSON.getJSON(je); 
     } 
     catch (Exception ue) { 

      progressDialog.dismiss(); 
      activity.showAlert("Please check internet connection."); 
      exception = true; 
      return Excpetion2JSON.getJSON(ue); 
     } 

    } //end of doInBackground 

    @Override 
    protected void onPostExecute(JSONObject response) { 
     super.onPostExecute(response); 

     if (response.has("message")) 
     { 
      try { 
       if(response.getString("message").equalsIgnoreCase(KEY_SUCCESS1)){ 
        // Toast.makeText(mContext,"success", Toast.LENGTH_LONG).show(); 

        contactListArray = response.getJSONArray("contacts"); 

        contactDb = new ContactTableHelper(mContext); 

        for (int i = 0; i < contactListArray.length(); i++) { 
         JSONObject subObject1 = contactListArray.getJSONObject(i); 

         Contact contact = new Contact(); 
         JSONObject subObject = subObject1; 
         String contactName = subObject.getString("user_name"); 
         //name of the attribute in response 
         String pass = subObject.getString("password"); 
         String contactId = subObject.getString("user_id"); 
         String contactMobile = subObject.getString("mobile_no"); 
         String contactEmailId = subObject.getString("email_id"); 
         String contactProfile = subObject.getString("profile_image"); 
         String fullName = subObject.getString("full_name"); 
         String jobTitle = subObject.getString("job_title"); 
         String homeAddress = subObject.getString("home_address"); 
         String workPhone = subObject.getString("work_phone"); 
         String workAddress = subObject.getString("work_address"); 
         String company = subObject.getString("company"); 

         contact.setmThumbnail(contactProfile); 
         contact.setmUserName(contactName); 
         contact.setmMobileNo(contactMobile); 
         contact.setmEmailId(contactEmailId); 
         contact.setmProfileImage(contactProfile); 
         contact.setContactId(contactId); 
         contact.setmHomeAddress(homeAddress); 
         contact.setmFullName(fullName); 
         contact.setmJobTitle(jobTitle); 
         contact.setmWorkAddress(workAddress); 
         contact.setmWorkPhone(workPhone); 
         contact.setmPass(pass); 
         contact.setmCompany(company); 

         contactList.add(contact);//adding string to arraylist 

         contactDb.addContact(new Contact(contactId,contactName,pass,contactMobile,contactEmailId,contactProfile,fullName,jobTitle,workAddress,workPhone,homeAddress,company)); 

         contactDb.close(); 
        } 
        contactGetCallBack.doPostExecute(contactList); 

        progressDialog.dismiss(); 
       } 
       else if(response.getString("message").equalsIgnoreCase("Contact list is empty")){ 

        progressDialog.dismiss(); 
        activity.showAlert("You do not have any contacts yet."); 
       } 
      } 
      catch (JSONException e) 
      { 
       e.printStackTrace(); 
       // progressDialog.dismiss(); 
      // activity.showAlert("Please check internet connection."); 

      } 
      if(exception) 
      { 
       activity.showAlert("Please check internet connection."); 
      } 
     } 
    } 
    public boolean isOnline() { 
     ConnectivityManager cm = 
       (ConnectivityManager)mContext.getSystemService(Context.CONNECTIVITY_SERVICE); 
     NetworkInfo netInfo = cm.getActiveNetworkInfo(); 
     return netInfo != null && netInfo.isConnectedOrConnecting(); 
    } 
    //end of onPostExecute 
} 

我也有Exception2Json類

public class Excpetion2JSON { 
    public static JSONObject getJSON(Exception e) { 
    try{ 
     JSONObject json = new JSONObject(); 
     json.put("result", -4); 
     json.put("message", e.getMessage()); 
     return json; 
    } catch(JSONException je) { 
     return null; 
    } 
} 
} 

而且UnexpectedServerException類:

public class UnexpectedServerException extends Exception { 
    public UnexpectedServerException(String msg) { 
     super(msg); 
    } 
} 
+1

您是否在清單文件中添加了Internet權限 – Pavya

+0

是的,我已添加。 @Pravin – Sid

+0

互聯網連接的作品,我想抓住例外。 – Sid

回答

0

添加這些例外您sendRequest將方法,無論是現有的catch塊或者只是改變它catch (Exception e)

+0

你可以給一個演示代碼嗎? – Sid

1

您的網絡調用是在後臺啓動(異步模式),所以您應該在doInBackground中使用try catch,並在GetContactsAsyncTask類中設置一個變量,它將檢查onPostExecute以返回適當的值。 認爲onPostExecute將在UiThread上運行。

+0

你能檢查編輯過的問題嗎? – Sid

+0

用try catch塊捕獲doInBackground中的異常,並將其設置爲GetContactsAsyncTask類的異常字段。之後,您應該檢查onPostExecute方法中的異常類字段,如下所示: if(異常instanceof MalformedServerException)exception.getSomeCustomViolations(); } else if(異常instanceof java.net.ConnectionException)exception.getSomeOtherCustomViolations(); } and ... –

+0

但是,如果我嘗試在doInbackground方法中捕獲UnnownKnownHost異常,它會給我錯誤,指出此異常不會在此處引發。您能否請我演示代碼 – Sid

相關問題