Asynctask中的HTTPRetryHandler

时间:2012-01-28 15:38:27

标签: android httpclient android-asynctask

首先,对不起,如果代码看起来很乱,我试着缩进,但似乎我需要更多练习。

我在AsyncTask(doInBackground)中做了3个HTTPS请求。

每个请求都会从网站上获取soms数据。

我试图找出一个HTTPRetryHandler,它会重试每个请求3次。 我已经找到了一个很好的example,但我不知道如何将其应用到我的代码中。

非常感谢任何帮助,谢谢。

我为每个请求使用相同的HTTPClient:

public HttpClient getHttpClient() { 

 DefaultHttpClient client = null;

  ResponseCache.setDefault(null);

try {  





KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); 
            trustStore.load(null, null); 
            SSLSocketFactory sf = new MySSLSocketFactory(trustStore); 
            sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); 

            // Setting up parameters 
            HttpParams params = new BasicHttpParams(); 
            params.setParameter(ConnManagerPNames.MAX_TOTAL_CONNECTIONS, 30); // default 30
            params.setParameter(ConnManagerPNames.MAX_CONNECTIONS_PER_ROUTE, new ConnPerRouteBean(30)); // default 30
            //params.setParameter(HttpProtocolParams.USE_EXPECT_CONTINUE, false); 
            HttpProtocolParams.setUseExpectContinue(params, false);
            HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); 
            HttpProtocolParams.setContentCharset(params, "UTF-8"); 

            // Setting timeout 
            HttpConnectionParams.setConnectionTimeout(params, 30000); 
            HttpConnectionParams.setSoTimeout(params, 30000); 

            // Registering schemes for both HTTP and HTTPS 
            SchemeRegistry registry = new SchemeRegistry(); 
            registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80)); 
            registry.register(new Scheme("https", sf, 443)); 

            // Creating thread safe client connection manager 
            ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, registry); 

            // Creating HTTP client 
            client  = new DefaultHttpClient(ccm, params); 

        } catch (Exception e) { 
            client = new DefaultHttpClient(); 
            Toast.makeText(AndroidLogin.this, "Problem with connection!", Toast.LENGTH_LONG).show(); 
        } 

        return client; 
    }

doInBackground中的示例调用:

/******* 2nd HTTP Request *******/
                try
                {
                    HttpPost request1 = new HttpPost("some webpage");
                    HttpResponse response1 = httpClient.execute(request1); 

                    InputStream inputStreamActivity1 = response1.getEntity().getContent();  
                    BufferedReader reader1 = new BufferedReader(new InputStreamReader(inputStreamActivity1));
                    StringBuilder sb1 = new StringBuilder();
                    String line1 = null;
                    String lookUp1 = "</response>";

                    while ((line1 = reader1.readLine()) != null) 
                    {
                        sb1.append(line1);
                        if (line1.indexOf(lookUp1)!= -1)
                        {
                            System.out.println("Found: </response>");
                            HttpRequest2 = "success";
                        }
                    }
                    STRINGBUILD_REQUEST2 = sb1.toString();
                    inputStreamActivity1.close();
                    publishProgress(response1.toString().length());

                } catch(SocketTimeoutException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                    Log.e("TAG: ", "SocketTimeoutException occured during HTTP request 2!");
                }
                /************* END 2nd HTTP Request *****************/

1 个答案:

答案 0 :(得分:0)

我能够通过将以下代码放在我的HTTPClient中来解决这个问题。

由于setUseExpectContinue似乎无法解决问题。

HttpRequestRetryHandler retryHandler = new HttpRequestRetryHandler() {

            @Override
            public boolean retryRequest(IOException exception, int executionCount, HttpContext context) {
                // TODO Auto-generated method stub
                if(executionCount >= 10) { // Retry 10 times        
                    return false;                 
                    } 
                if(exception instanceof SocketTimeoutException)
                {                     
                    return true;                 
                    } 
                else if (exception instanceof ClientProtocolException)
                {                     
                    return true;                 
                    }  
                return false;             
                }  
            };   

        client.setHttpRequestRetryHandler(retryHandler);