考虑下一种情况。
我正在通过我的应用程序向服务器发布内容。例如,我已经建立了连接并将超时重新设置为3000ms。
在互联网连接速度慢的情况下,用户应用程序将引发异常,该异常将被处理以通知用户请求已超时,但实际上请求和数据已由服务器成功处理。
当然,我会将超时时间设置为3000ms以上,仅当我注意到此问题时才将其用于测试目的,但我不禁想知道如何处理此问题?
最佳答案
第一步是将我们的api发送到应用程序的控件状态代码,如果此代码为'statusCode == 200',我们就可以知道连接的开始和结束正确。第二步,我的服务器将向我发送一个自定义答案。例如,如果我可以读取所有内容并且我们正确完成了连接,那么我将“ OK”作为来自服务器的响应实体发送。您可以在下面看到我的代码:
private String Sync3_GetRequest_NewLocalInformation(String url,String id,List<NameValuePair> ListOfValues){
//Declaration of variables
DefaultHttpClient httpClient;
HttpPost Request = new HttpPost(url);
HttpResponse Response;
HttpParams httpParameters = new BasicHttpParams();
httpParameters.setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
String Result = "Completed";
// Set the timeout in milliseconds until a connection is established.
// The default value is zero, that means the timeout is not used.
int timeoutConnection = 3000;
HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
// Set the default socket timeout (SO_TIMEOUT)
// in milliseconds which is the timeout for waiting for data.
int timeoutSocket = 60000;
HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
httpClient = new DefaultHttpClient(httpParameters);
try {
HttpEntity entity = new UrlEncodedFormEntity(ListOfValues);
Request.setHeader(entity.getContentType());
Request.setEntity(entity);
Response = httpClient.execute(Request);
if (Response.getStatusLine().getStatusCode() == 200) {
String EntityResult = EntityUtils.toString(Response.getEntity());
Log.e("-- Sync_Class.Sync3_GetRequest_NewLocalInformation --", EntityResult);
if(EntityResult.contains("\"message\":OK")){
//My code
}
else{
Log.e("-- Sync_Class.Sync3_GetRequest_NewLocalInformation --", "Invalid code");
}
return Result;
}
else{
MainActivity.CanUpdate = true;
Log.e("-- Sync_Class.Sync3_GetRequest_NewLocalInformation --", "Invalid Status Code");
throw new RuntimeException("Invalid Status Code");
}
}
catch (Exception ex){
MainActivity.CanUpdate = true;
Log.e("-- Sync_Class.Sync3_GetRequest_NewLocalInformation --", "Exception",ex);
return ex.toString();
}
}
我使用简单的步骤来控制此问题。告诉我是否能帮助您,祝您好运!
关于php - 处理实际上已成功由服务器处理的HTTP请求超时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30773380/