Asynctask 中的 HTTPRetryHandler

发布于 2024-12-29 15:43:39 字数 3907 浏览 1 评论 0原文

首先,抱歉,如果代码看起来很混乱,我尝试缩进,但似乎我需要更多练习。

我正在 AsyncTask(doInBackground) 中执行 3 个 HTTPS 请求。

每个请求都会从网站获取一些数据。

我试图找出一个 HTTPRetryHandler 来重试每个请求 3 次。 我已经找到了一个不错的 示例 但我不知道如何将其应用到我的代码中。

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

我对每个请求使用相同的 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 *****************/

First of all, sorry if the code looks messy, i tried to indent but it seems i need more practice.

I am doing 3 HTTPS requests in a AsyncTask(doInBackground).

Every requests grabs soms data from a website.

I am trying to figure out to make a HTTPRetryHandler which retries every request 3 times.
I already found a nice example but i don`t know how to apply this to my code.

Any help with is really appreciated, thank you.

I use the same HTTPClient for every request:

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

Example call in 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 *****************/

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

请远离我 2025-01-05 15:43:39

我可以通过将以下代码放入我的 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);

I was able to solve this by myself by putting the following code in my HTTPClient.

As setUseExpectContinue does not seem to solve the problem.

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);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文