我正在调用服务器任务,我想捕获所有与网络相关的异常。我得到了java.net.ConnectException
。我不是从它的投掷位置到哪里捕获的。
服务器类:
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
如何捕获UnknownHostException
,java.net.ConnectionException
,UnexpectedServerException
,MalformedServerException
的所有例外情况?
我试图在postExecute
之后的JSONException
方法中捕获异常,但它显示此处未抛出异常..
请帮忙。谢谢..
编辑:我尝试过类似这样的东西来添加一个布尔变量,并在异常抛出时使其成立但不起作用..请检查; 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);
}
}
答案 0 :(得分:1)
您的网络调用是在后台启动的(异步模式),因此您应该在doInBackground中使用try catch并在GetContactsAsyncTask类中设置一个变量,它将检查onPostExecute以返回适当的值。 考虑onPostExecute将在UiThread上运行。
答案 1 :(得分:0)
将这些例外添加到您的sendRequest方法中,或者添加到现有的catch块中,或者只需将其更改为catch (Exception e)
。