处理具有timedout的http请求,而实际请求由服务器成功处理

时间:2015-06-11 06:37:37

标签: php android httpresponse

考虑下一个案例。

我通过我的应用程序向服务器发布了一些内容。我已经建立了连接并将超时设置为3000毫秒。

在互联网连接速度较慢的情况下,用户应用程序将抛出异​​常,该异常将被处理以通知用户请求已超时,但实际上服务器已成功处理了请求和数据。

当然我会将超时时间设置为超过3000毫秒,我只是在注意到这个问题时才将其用于测试目的,但我不禁想知道如何处理这个问题?

1 个答案:

答案 0 :(得分:1)

第一步是将我们的api发送到应用的控制状态代码,如果此代码是“statusCode == 200'我们可以知道连接的开始和结束是正确的。作为第二步,我这样做,我的服务器将发送给我一个自定义的答案。例如,如果我可以阅读所有内容并且我们正确完成了连接,那么我发送“确定”#39;作为我服务器响应的实体。您可以在下面看到我的代码:

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();
    }
}

我使用简单的步骤来控制这个问题。告诉我,如果我帮助你,祝你好运!