Example usage for org.apache.http.client HttpRequestRetryHandler retryRequest

List of usage examples for org.apache.http.client HttpRequestRetryHandler retryRequest

Introduction

In this page you can find the example usage for org.apache.http.client HttpRequestRetryHandler retryRequest.

Prototype

boolean retryRequest(IOException exception, int executionCount, HttpContext context);

Source Link

Document

Determines if a method should be retried after an IOException occurs during execution.

Usage

From source file:com.corebase.android.framework.http.client.AsyncHttpRequest.java

private void makeRequestWithRetries() throws IOException {
    // This is an additional layer of retry logic lifted from droid-fu
    // See:// w w w .  ja va2 s. c om
    // https://github.com/kaeppler/droid-fu/blob/master/src/main/java/com/github/droidfu/http/BetterHttpRequestBase.java
    boolean retry = true;
    IOException cause = null;
    HttpRequestRetryHandler retryHandler = client.getHttpRequestRetryHandler();
    while (retry) {
        try {
            makeRequest();
            return;
        } catch (UnknownHostException e) {
            if (responseHandler != null) {
                responseHandler.sendFailureMessage(mycontext, e, "can't resolve host");
            }
            Log.i("msg", "1");
            return;
        } catch (SocketException e) {
            // Added to detect host unreachable
            if (responseHandler != null) {
                responseHandler.sendFailureMessage(mycontext, e, "can't resolve host");
            }
            Log.i("msg", "2");
            return;
        } catch (SocketTimeoutException e) {
            if (responseHandler != null) {
                responseHandler.sendFailureMessage(mycontext, e, "socket time out");
            }
            Log.i("msg", "3");
            return;
        } catch (IOException e) {
            cause = e;
            retry = retryHandler.retryRequest(cause, ++executionCount, context);
            Log.i("msg", "4");
        } catch (NullPointerException e) {
            // there's a bug in HttpClient 4.0.x that on some occasions
            // causes
            // DefaultRequestExecutor to throw an NPE, see
            // http://code.google.com/p/android/issues/detail?id=5255
            cause = new IOException("NPE in HttpClient" + e.getMessage());
            Log.i("msg", "4");
            retry = retryHandler.retryRequest(cause, ++executionCount, context);
        } catch (Exception e) {
            e.printStackTrace();
            cause = new IOException("Exception" + e.getMessage());
            retry = retryHandler.retryRequest(cause, ++executionCount, context);
            Log.i("msg", "4");
        }
    }

    // ??
    // ConnectException ex = new ConnectException();
    // ex.initCause(cause);
    throw cause;
}

From source file:com.pyj.http.AsyncHttpRequest.java

private void makeRequestWithRetries() throws ConnectException {
    // This is an additional layer of retry logic lifted from droid-fu
    // See: https://github.com/kaeppler/droid-fu/blob/master/src/main/java/com/github/droidfu/http/BetterHttpRequestBase.java
    boolean retry = true;
    IOException cause = null;/*from  w  w w  .j a v  a2 s.  c  om*/
    HttpRequestRetryHandler retryHandler = client.getHttpRequestRetryHandler();
    while (retry) {
        try {
            makeRequest();
            return;
        } catch (UnknownHostException e) {
            if (responseHandler != null) {
                responseHandler.sendFailureMessage(
                        new HupuHttpException("???????"), (String) null,
                        reqType);
            }
            return;
        } catch (SocketException e) {
            // Added to detect host unreachable
            if (responseHandler != null) {
                responseHandler.sendFailureMessage(
                        new HupuHttpException("????"), (String) null,
                        reqType);
            }
            return;
        } catch (SocketTimeoutException e) {
            if (responseHandler != null) {
                responseHandler.sendFailureMessage(
                        new HupuHttpException("????"), (String) null,
                        reqType);
            }
            return;
        } catch (IOException e) {
            cause = e;
            retry = retryHandler.retryRequest(cause, ++executionCount, context);
        } catch (NullPointerException e) {
            // there's a bug in HttpClient 4.0.x that on some occasions causes
            // DefaultRequestExecutor to throw an NPE, see
            // http://code.google.com/p/android/issues/detail?id=5255
            cause = new IOException("NPE in HttpClient" + e.getMessage());
            retry = retryHandler.retryRequest(cause, ++executionCount, context);
        }
    }

    // no retries left, crap out with exception
    ConnectException ex = new ConnectException();
    ex.initCause(cause);
    throw ex;
}

From source file:cn.isif.util_plus.http.HttpHandler.java

@SuppressWarnings("unchecked")
private ResponseInfo<T> sendRequest(HttpRequestBase request) throws HttpException {

    HttpRequestRetryHandler retryHandler = client.getHttpRequestRetryHandler();
    while (true) {

        if (autoResume && isDownloadingFile) {
            File downloadFile = new File(fileSavePath);
            long fileLen = 0;
            if (downloadFile.isFile() && downloadFile.exists()) {
                fileLen = downloadFile.length();
            }// www  .  j ava 2s. c  o  m
            if (fileLen > 0) {
                request.setHeader("RANGE", "bytes=" + fileLen + "-");
            }
        }

        boolean retry = true;
        IOException exception = null;
        try {
            requestMethod = request.getMethod();
            if (HttpUtils.sHttpCache.isEnabled(requestMethod)) {
                String result = HttpUtils.sHttpCache.get(requestUrl);
                if (result != null) {
                    return new ResponseInfo<T>(null, (T) result, true);
                }
            }

            ResponseInfo<T> responseInfo = null;
            if (!isCancelled()) {
                HttpResponse response = client.execute(request, context);
                responseInfo = handleResponse(response);
            }
            return responseInfo;
        } catch (UnknownHostException e) {
            exception = e;
            retry = retryHandler.retryRequest(exception, ++retriedCount, context);
        } catch (IOException e) {
            exception = e;
            retry = retryHandler.retryRequest(exception, ++retriedCount, context);
        } catch (NullPointerException e) {
            exception = new IOException(e.getMessage());
            exception.initCause(e);
            retry = retryHandler.retryRequest(exception, ++retriedCount, context);
        } catch (HttpException e) {
            throw e;
        } catch (Throwable e) {
            exception = new IOException(e.getMessage());
            exception.initCause(e);
            retry = retryHandler.retryRequest(exception, ++retriedCount, context);
        }
        if (!retry) {
            throw new HttpException(exception);
        }
    }
}

From source file:com.adis.tools.http.HttpHandler.java

@SuppressWarnings("unchecked")
private ResponseInfo<T> sendRequest(HttpRequestBase request) throws HttpException {

    HttpRequestRetryHandler retryHandler = client.getHttpRequestRetryHandler();
    while (true) {

        if (autoResume && isDownloadingFile) {
            downloadFile = new File(fileSavePath);
            fileLen = 0;//from  w w w  .ja va  2 s . c o m
            if (downloadFile.isFile() && downloadFile.exists()) {
                fileLen = downloadFile.length();
            }
            if (fileLen > 0) {
                request.setHeader("RANGE", "bytes=" + fileLen + "-");
            }
        }

        boolean retry = true;
        IOException exception = null;
        try {
            requestMethod = request.getMethod();
            if (HttpUtils.sHttpCache.isEnabled(requestMethod)) {
                String result = HttpUtils.sHttpCache.get(requestUrl);
                if (result != null) {
                    return new ResponseInfo<T>(null, (T) result, true);
                }
            }

            ResponseInfo<T> responseInfo = null;
            if (!isCancelled()) {
                HttpResponse response = client.execute(request, context);
                responseInfo = handleResponse(response);
            }
            return responseInfo;
        } catch (UnknownHostException e) {
            exception = e;
            retry = retryHandler.retryRequest(exception, ++retriedCount, context);
        } catch (IOException e) {
            exception = e;
            retry = retryHandler.retryRequest(exception, ++retriedCount, context);
        } catch (NullPointerException e) {
            exception = new IOException(e.getMessage());
            exception.initCause(e);
            retry = retryHandler.retryRequest(exception, ++retriedCount, context);
        } catch (HttpException e) {
            throw e;
        } catch (Throwable e) {
            exception = new IOException(e.getMessage());
            exception.initCause(e);
            retry = retryHandler.retryRequest(exception, ++retriedCount, context);
        }
        if (!retry) {
            throw new HttpException(exception);
        }
    }
}

From source file:com.drive.student.xutils.http.HttpHandler.java

@SuppressWarnings("unchecked")
private com.drive.student.xutils.http.ResponseInfo<T> sendRequest(HttpRequestBase request)
        throws HttpException {

    HttpRequestRetryHandler retryHandler = client.getHttpRequestRetryHandler();
    while (true) {

        if (autoResume && isDownloadingFile) {
            File downloadFile = new File(fileSavePath);
            long fileLen = 0;
            if (downloadFile.isFile() && downloadFile.exists()) {
                fileLen = downloadFile.length();
            }/*  w  w  w  . jav a2s  .  c  o m*/
            if (fileLen > 0) {
                request.setHeader("RANGE", "bytes=" + fileLen + "-");
            }
        }

        boolean retry = true;
        IOException exception = null;
        try {
            requestMethod = request.getMethod();
            if (HttpUtils.sHttpCache.isEnabled(requestMethod)) {
                String result = HttpUtils.sHttpCache.get(requestUrl);
                if (result != null) {
                    return new com.drive.student.xutils.http.ResponseInfo<T>(null, (T) result, true);
                }
            }

            com.drive.student.xutils.http.ResponseInfo<T> responseInfo = null;
            if (!isCancelled()) {
                HttpResponse response = client.execute(request, context);
                responseInfo = handleResponse(response);
            }
            return responseInfo;
        } catch (UnknownHostException e) {
            exception = e;
            retry = retryHandler.retryRequest(exception, ++retriedCount, context);
        } catch (IOException e) {
            exception = e;
            retry = retryHandler.retryRequest(exception, ++retriedCount, context);
        } catch (NullPointerException e) {
            exception = new IOException(e.getMessage());
            exception.initCause(e);
            retry = retryHandler.retryRequest(exception, ++retriedCount, context);
        } catch (HttpException e) {
            throw e;
        } catch (Throwable e) {
            exception = new IOException(e.getMessage());
            exception.initCause(e);
            retry = retryHandler.retryRequest(exception, ++retriedCount, context);
        }
        if (!retry) {
            throw new HttpException(exception);
        }
    }
}

From source file:com.youzu.android.framework.http.HttpHandler.java

@SuppressWarnings("unchecked")
private ResponseInfo<T> sendRequest(HttpRequestBase request) throws HttpException {

    HttpRequestRetryHandler retryHandler = client.getHttpRequestRetryHandler();
    while (true) {

        if (autoResume && isDownloadingFile) {
            File downloadFile = new File(fileSavePath);
            long fileLen = 0;
            if (downloadFile.isFile() && downloadFile.exists()) {
                fileLen = downloadFile.length();
            }/*from   w  w w.j av a2 s.c o m*/
            if (fileLen > 0) {
                request.setHeader("RANGE", "bytes=" + fileLen + "-");
            }
        }

        boolean retry = true;
        IOException exception = null;
        try {
            //                ResponseInfo<T> responseInfo = null;
            //                if (!isCancelled()) {
            //                    HttpResponse response = client.execute(request, context);
            //                    responseInfo = handleResponse(response);
            ////                    CookieStore store = client.getCookieStore();
            //                }
            //                return responseInfo;

            requestMethod = request.getMethod();
            if (HttpUtils.sHttpCache.isEnabled(requestMethod)) {
                String result = HttpUtils.sHttpCache.get(requestUrl);
                if (result != null) {
                    return new ResponseInfo<T>(null, (T) result, true);
                }
            }
            ResponseInfo<T> responseInfo = null;
            if (!isCancelled()) {
                HttpResponse response = client.execute(request, context);
                responseInfo = handleResponse(response);
            }
            return responseInfo;
        } catch (UnknownHostException e) {
            Log.e("APP", "HttpHandler sendRequest UnknownHostException:" + e.getMessage());

            exception = e;
            retry = retryHandler.retryRequest(exception, ++retriedCount, context);
        } catch (IOException e) {
            Log.e("APP", "HttpHandler sendRequest IOException: " + e.toString());

            exception = e;
            retry = retryHandler.retryRequest(exception, ++retriedCount, context);
        } catch (NullPointerException e) {
            Log.e("APP", "HttpHandler sendRequest NullPointerException:" + e.getMessage());

            exception = new IOException(e.getMessage());
            exception.initCause(e);
            retry = retryHandler.retryRequest(exception, ++retriedCount, context);
        } catch (HttpException e) {
            Log.e("APP", "HttpHandler sendRequest HttpException:" + e.getMessage());

            throw e;
        } catch (Throwable e) {
            Log.e("APP", "HttpHandler sendRequest Throwable:" + e.getMessage());

            exception = new IOException(e.getMessage());
            exception.initCause(e);
            retry = retryHandler.retryRequest(exception, ++retriedCount, context);
        }

        Log.e("APP", "retry:" + retry);

        if (!retry) {
            HttpException httpException = new HttpException(exception);
            Log.e("APP", "HttpHandler sendRequest HttpException:" + httpException.getMessage());
            //                callback.onFailure(httpException,httpException.getMessage());
            throw httpException;
        }
    }
}

From source file:net.tsz.afinal.http.HttpHandler.java

private void makeRequestWithRetries(HttpUriRequest request) throws IOException {
    if (isResume && targetUrl != null) {
        File downloadFile = new File(targetUrl);
        long fileLen = 0;
        if (downloadFile.isFile() && downloadFile.exists()) {
            fileLen = downloadFile.length();
        }//  www  .j  a v a2s.  c  o m
        if (fileLen > 0)
            request.setHeader("RANGE", "bytes=" + fileLen + "-");
    }

    boolean retry = true;
    IOException cause = null;
    HttpRequestRetryHandler retryHandler = client.getHttpRequestRetryHandler();//?
    while (retry) {
        try {
            if (isCancelled()) {
                return;
            }

            //POST:?;GET:?
            String requestUrl = request.getURI().toString();
            String requestMethod = request.getMethod();
            ZLogger.d(String.format("<%d><%s> %s", executionCount, requestMethod, requestUrl));

            for (Header header : request.getAllHeaders()) {
                ZLogger.d(String.format("<%s>:<%s>", header.getName(), header.getValue()));
            }

            //??url
            StringBuilder requestParams = new StringBuilder();
            if (requestMethod.equals(POST)) {
                HttpEntityEnclosingRequestBase requestBase = (HttpEntityEnclosingRequestBase) request;
                if (requestBase != null) {
                    HttpEntity entity = requestBase.getEntity();
                    if (entity != null) {
                        InputStream is = entity.getContent();
                        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
                        String line = null;
                        try {
                            while ((line = reader.readLine()) != null) {
                                //                            sb.append(line + "/n");
                                //                                Log.d("Nat: makeRequestWithRetries.request.Params.line", line);
                                requestParams.append(line);
                            }
                        } catch (IOException e) {
                            e.printStackTrace();
                            ZLogger.ef(e.toString());
                        } finally {
                            try {
                                is.close();
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        }
                    }
                    //                        byte[] paramsArray = EntityUtils.toByteArray(entity);
                    //                        String paramsStr = EntityUtils.toString(entity, "UTF-8");
                    //                        Log.d("Nat: makeRequestWithRetries.request.Params(2)", paramsStr);
                    //                        Log.d("Nat: makeRequestWithRetries.request.Params(3)", EntityUtils.toString(entity));
                }

                //                    Log.d("Nat: makeRequestWithRetries.request.Params(RAW)", requestParams.toString());
            }

            //
            HttpResponse response = client.execute(request, context);
            //                for(Header header : response.getAllHeaders()){
            //                    Log.d("Nat", String.format(" makeRequestWithRetries.respoonse.header <%s><%s>", header.getName(), header.getValue()));
            //                }

            if (isCancelled()) {
                ZLogger.d("Nat: makeRequestWithRetries", "request caneled.");
                return;
            }

            //POST:?;GET:?
            request.getRequestLine();//GET
            ZLogger.d(request.getRequestLine().toString());
            /*if (request.getMethod().equals("post")) {
            HttpParams params = request.getParams();
             params.setParameter(NetFactory.CLIENTSESSION, "");
            request.snetParams(params);
            }*/

            //?????()
            //executionCount < 1,?????
            if (response.containsHeader("needLogin")/* && executionCount < 1*/) {
                //?url?JSSIONID??cookie.
                //?(?),sessionId
                String newSid = MfhLoginService.get().doLogin();
                if (newSid == null) {
                    //TODO
                    //,?
                    //                        Intent intent = new Intent(Constants.ACTION_REDIRECT_TO_LOGIN_H5);
                    //                        BizApplication.getAppContext().sendBroadcast(intent);
                    //                        break;
                } else {
                    String cookie = String.format("%s=%s", FinalHttp.KEY_JSESSIONID, newSid);
                    request.addHeader(FinalHttp.HEADER_SET_COOKIE, cookie);
                    request.addHeader(FinalHttp.HEADER_COOKIE, cookie);
                    request.addHeader(FinalHttp.HEADER_cookie, cookie);
                    // ?
                    //                        MsgBridgeUtil.register();

                    if (requestMethod.equals(POST)) {
                        //                        //EntityJSSIONID
                        String newParams = replaceParam(requestParams.toString(), JSESSIONID, newSid);
                        //                            HttpEntity entity = new StringEntity(newParams);
                        HttpEntity entity = convertToAjaxParams(newParams).getEntity();
                        ((HttpEntityEnclosingRequestBase) request).setEntity(entity);
                    } else if (requestMethod.equals(GET)) {
                        //URLJSSIONID
                        String newRequestUrl = replaceParam(requestUrl, JSESSIONID, newSid);
                        //                            newRequestUrl = replaceParam(newRequestUrl, "lastupdate", "0");
                        URI uri = new URI(newRequestUrl);
                        //                            Log.d("Nat: makeRequestWithRetries.autoLogin.URI", uri.toString());
                        //                                HttpEntityEnclosingRequestBase requestFact = (HttpEntityEnclosingRequestBase)request;
                        //                                requestFact.setURI(uri);
                        ((HttpEntityEnclosingRequestBase) request).setURI(uri);
                    }
                }

                //TODO,?
                retry = (++executionCount <= MAX_RETRY_TIMES)
                        || retryHandler.retryRequest(new IOException("Exception"), executionCount, context);
                //                    ZLogger.d(String.format("%s  %d", retry ? "?" : "??", executionCount));
                if (retry) {
                    continue;
                }
            }

            //?
            handleResponse(response);
            return;
        } catch (UnknownHostException e) {
            ZLogger.e("UnknownHostException:" + e.toString());
            publishProgress(UPDATE_FAILURE, e, "unknownHostExceptioncan't resolve host");
            return;
        } catch (IOException e) {
            ZLogger.e("IOException: " + e.toString());
            cause = e;
            retry = retryHandler.retryRequest(cause, ++executionCount, context);
            publishProgress(UPDATE_FAILURE, e, "unknownHostExceptioncan't resolve host");
        } catch (NullPointerException e) {
            if (e != null) {
                ZLogger.e("NullPointerException: " + e.toString());
                // here's a bug in HttpClient 4.0.x that on some occasions causes
                // DefaultRequestExecutor to throw an NPE, see
                // http://code.google.com/p/android/issues/detail?id=5255
                cause = new IOException("NPE in HttpClient: " + e.getMessage());
                retry = retryHandler.retryRequest(cause, ++executionCount, context);
            } else {
                ZLogger.e("NullPointerException: e is null");
            }
            publishProgress(UPDATE_FAILURE, e, "unknownHostExceptioncan't resolve host");
        } catch (Exception e) {
            ZLogger.e("Exception: " + e.toString());
            cause = new IOException("Unhandled Exception" + e.getMessage());
            retry = retryHandler.retryRequest(cause, ++executionCount, context);
            publishProgress(UPDATE_FAILURE, e, "unknownHostExceptioncan't resolve host");
        }
    }

    // cleaned up to throw IOException
    if (cause != null) {
        throw cause;
    }
    //        else{
    //            //TODO
    //            throw new IOException("");
    //        }
}