我有一个Async任务,用于检查用户会话。此任务负责使用方法联系服务器 - 两者都列在下面:
public class SessionChecker extends AsyncTask<Void, Void, String> {
@Override
protected void onPreExecute() {
super.onPreExecute();
}
@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
Intent intent;
if (result.equalsIgnoreCase("exception")) {
//We got an exception in URL Connection - letus restart the task -- this is recursive
new SessionChecker().execute();
} else if (result.equalsIgnoreCase("server error")) {
//We got an exception in URL Connection - letus restart the task -- this is recursive
new SessionChecker().execute();
} else {
try {
JSONObject jObj = new JSONObject(result);
if (!TextUtils.isEmpty(result)) {
String message = jObj.getString("message");
if (message.equalsIgnoreCase("failure")) {
intent = new Intent(AppInitializer.this, AppWebViewLogin.class);
startActivity(intent);
} else if (message.equalsIgnoreCase("success")) {
intent = new Intent(AppInitializer.this, NavigationMasterActivity.class);
startActivity(intent);
}
}
} catch (JSONException ex) {
//Malformed JSON - letus restart the task -- this is recursive
new SessionChecker().execute();
}
}
}
@Override
protected String doInBackground(Void... params) {
DomainManager domainManager = new DomainManager(AppInitializer.this);
return UniversalNetworkConnection.simplePost(domainManager.getDomain() + getResources().getString(R.string.url_check_session));
}
}
这是我的网址连接方法:
public static String simplePost(String myurl) {
HttpsURLConnection conn = null;
try {
SSLContext sslcontext = SSLContext.getInstance("TLSv1");
sslcontext.init(null, null, null);
SSLSocketFactory NoSSLv3Factory = new NoSSLv3SocketFactory(sslcontext.getSocketFactory());
HttpsURLConnection.setDefaultSSLSocketFactory(NoSSLv3Factory);
StringBuffer response;
URL url = new URL(myurl);
conn = (HttpsURLConnection) url.openConnection();
// conn.setReadTimeout(90000);
// conn.setConnectTimeout(900000);
conn.setRequestProperty("Content-Type", "application/json");
CookieManager cookieManager = CookieManager.getInstance();
String cookie = cookieManager.getCookie(new URL(myurl).getHost());
conn.setDoOutput(true);
conn.setRequestProperty("Cookie", cookie);
conn.setRequestMethod("POST");
int responseCode = conn.getResponseCode();
switch (responseCode) {
case 200:
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String inputLine;
response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
return response.toString();
default:
return "server error";
}
} catch (IOException | java.security.KeyManagementException | java.security.NoSuchAlgorithmException ex) {
ex.printStackTrace();
return "exception";
} finally {
if (conn != null) {
try {
conn.disconnect();
} catch (Exception ex) {
ex.printStackTrace();
return "exception";
}
}
}
}
我已尝试递归处理异常 - 发生异常 - 异步任务被重新加载,我如何改进这一点,我不确定我这样做是否是最好的做法?任何提示/解决方案/提示都会非常有用。