Обрабатывать, если ответ задерживается в HTTP-соединении в Android
Я делаю запрос HTTP. Я хочу поставить галочку, что если я не получу ответ в течение 10 секунд, я выйду из цикла. Ниже мой код. Что может быть самым простым способом сделать это при выполнении HTTP-запроса. Предложения приветствуются. Если вы можете дать мне знать, где именно я должен включить эти предложения в мой код, было бы чрезвычайно полезно. Спасибо
protected String doInBackground(String... params) {
if (STATUS_STARTED != statusCode) {
return null;
}
final HttpClient client = new DefaultHttpClient();
String email = null;
String url = null;
try {
email = params[0];
url = params[1];
} catch (ArrayIndexOutOfBoundsException e) {
Log.e("LOG_TAG", "Invalid parameters are passed to task", e);
statusCode = STATUS_BADPARAM;
return null;
}
if ( (null == url) || (null == email)) {
Log.e("LOG_TAG", "One of input params is null: url=" + url + "; email=" + email);
statusCode = STATUS_BADPARAM;
return null;
}
if(email != null){
email = email.trim().replaceAll(" ", "");
//email = email.toLowerCase();
Log.d("EmailLowerCase", "EmailValidator" + email);
}
//url += REQUEST_PARAM_START + REQUEST_PARAM_EMAIL + email;
url += email;
Log.d("LOG_TAG", "Execute activation request to " + url);
HttpGet getRequest = null;
try {
getRequest = new HttpGet(url);
} catch (Exception e) {
Log.e("LOG_TAG", e.getMessage());
}
try {
try {
int timeoutConnection = 10 * 1000;
HttpConnectionParams.setConnectionTimeout(client.getParams(), timeoutConnection);
Log.d("LOG_TAG", "Execute activation request to " + url);
statusCode = STATUS_IN_PROGRESS;
HttpResponse response = client.execute(getRequest);
Log.d("LOG_TAG", "Activation request to " + url
+ " completed");
switch (response.getStatusLine().getStatusCode()) {
case HttpStatus.SC_OK:
case HttpStatus.SC_MULTI_STATUS:
case HttpStatus.SC_PARTIAL_CONTENT:
case HttpStatus.SC_RESET_CONTENT:
case HttpStatus.SC_CREATED:
case HttpStatus.SC_ACCEPTED:
case HttpStatus.SC_NON_AUTHORITATIVE_INFORMATION:
statusCode = STATUS_COMPLETED;
break;
case HttpStatus.SC_GATEWAY_TIMEOUT:
statusCode = STATUS_GATEWAY_TIMEOUT;
return "-1";
default:
Log.e("EmailValidator", "Error "
+ response.getStatusLine().getStatusCode()
+ " during activation, url=" + url);
statusCode = STATUS_ERROR;
break;
}
String responseStr = null;
final HttpEntity entityResponse = response.getEntity();
if (null != entityResponse) {
InputStream inputStream = null;
OutputStream outputStream = null;
final ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
try {
inputStream = entityResponse.getContent();
outputStream = new BufferedOutputStream(dataStream,
IO_BUFFER_SIZE);
copy(inputStream, outputStream);
outputStream.flush();
responseStr = dataStream.toString();
return responseStr;
} finally {
if (null != inputStream) {
inputStream.close();
}
if (null != outputStream) {
outputStream.close();
}
if (null != dataStream) {
dataStream.close();
}
entityResponse.consumeContent();
}
}
}
catch (ConnectTimeoutException e) {
getRequest.abort();
Log.d("ConnectionTimeOut","Connection timout occured");
} catch (IOException e) {
getRequest.abort();
Log.e("LOG_TAG", "I/O error during activation, url=" + url, e);
} catch (IllegalStateException e) {
getRequest.abort();
Log.e("LOG_TAG", "Incorrect URL: " + url);
} catch (Exception e) {
getRequest.abort();
Log.e("LOG_TAG", "Error during activation, url=" + url, e);
}
} catch (Exception e) {
Log.e("LOG_TAG", "Error during activation, url=" + url, e);
} catch (Throwable e) {
Log.e("LOG_TAG", "Error during activation, url=" + url, e);
}
Log.e("LOG_TAG", TRANSMITTING_ERROR);
return null;
}
2 ответа
Решение
Попробуйте добавить HttpConnection Timeout, как показано ниже
int timeoutConnection = 10 * 1000;
HttpConnectionParams.setConnectionTimeout(client.getParams(),
timeoutConnection);
РЕДАКТИРОВАТЬ:
Вы можете проверить, произойдет ли тайм-аут внутри блока catch. увидеть ниже
try {
Log.d("LOG_TAG", "Execute activation request to " + url);
statusCode = STATUS_IN_PROGRESS;
HttpResponse response = client.execute(getRequest);
Log.d("LOG_TAG", "Activation request to " + url
+ " completed");
switch (response.getStatusLine().getStatusCode()) {
case HttpStatus.SC_OK:
case HttpStatus.SC_MULTI_STATUS:
case HttpStatus.SC_PARTIAL_CONTENT:
case HttpStatus.SC_RESET_CONTENT:
case HttpStatus.SC_CREATED:
case HttpStatus.SC_ACCEPTED:
case HttpStatus.SC_NON_AUTHORITATIVE_INFORMATION:
statusCode = STATUS_COMPLETED;
break;
case HttpStatus.SC_GATEWAY_TIMEOUT:
statusCode = STATUS_GATEWAY_TIMEOUT;
return "-1";
default:
Log.e("EmailValidator", "Error "
+ response.getStatusLine().getStatusCode()
+ " during activation, url=" + url);
statusCode = STATUS_ERROR;
break;
}
String responseStr = null;
final HttpEntity entityResponse = response.getEntity();
if (null != entityResponse) {
InputStream inputStream = null;
OutputStream outputStream = null;
final ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
try {
inputStream = entityResponse.getContent();
outputStream = new BufferedOutputStream(dataStream,
IO_BUFFER_SIZE);
copy(inputStream, outputStream);
outputStream.flush();
responseStr = dataStream.toString();
return responseStr;
} finally {
if (null != inputStream) {
inputStream.close();
}
if (null != outputStream) {
outputStream.close();
}
if (null != dataStream) {
dataStream.close();
}
entityResponse.consumeContent();
}
}
}catch (ConnectTimeoutException e) {
Log.i("log","Connection timout occour");
} catch (IOException e) {
getRequest.abort();
Log.e("LOG_TAG", "I/O error during activation, url=" + url, e);
} catch (IllegalStateException e) {
getRequest.abort();
Log.e("LOG_TAG", "Incorrect URL: " + url);
} catch (Exception e) {
getRequest.abort();
Log.e("LOG_TAG", "Error during activation, url=" + url, e);
}
Обратитесь к этому сообщению, в нем есть подробности о методе AsyncTask.get(), который можно использовать в этом случае, чтобы подождать определенное время перед тем, как прекратить опрос сервера: -