Search in sources :

Example 56 with ConnectTimeoutException

use of org.apache.http.conn.ConnectTimeoutException in project RxJavaInAction by fengzhizi715.

the class RetryHandler method retryRequest.

@Override
public boolean retryRequest(IOException exception, int executionCount, HttpContext context) {
    if (executionCount >= 3) {
        // 如果已经重试了3次,就放弃
        return false;
    }
    if (exception instanceof NoHttpResponseException) {
        // 如果服务器丢掉了连接,那么就重试
        return true;
    }
    if (exception instanceof SSLHandshakeException) {
        // 不要重试SSL握手异常
        return false;
    }
    if (exception instanceof InterruptedIOException) {
        // 超时
        return true;
    }
    if (exception instanceof UnknownHostException) {
        // 目标服务器不可达
        return false;
    }
    if (exception instanceof ConnectTimeoutException) {
        // 连接被拒绝
        return false;
    }
    if (exception instanceof SSLException) {
        // ssl握手异常
        return false;
    }
    HttpClientContext clientContext = HttpClientContext.adapt(context);
    HttpRequest request = clientContext.getRequest();
    // 如果请求是幂等的,就再次尝试
    if (!(request instanceof HttpEntityEnclosingRequest)) {
        return true;
    }
    return false;
}
Also used : NoHttpResponseException(org.apache.http.NoHttpResponseException) HttpRequest(org.apache.http.HttpRequest) InterruptedIOException(java.io.InterruptedIOException) UnknownHostException(java.net.UnknownHostException) HttpEntityEnclosingRequest(org.apache.http.HttpEntityEnclosingRequest) HttpClientContext(org.apache.http.client.protocol.HttpClientContext) SSLException(javax.net.ssl.SSLException) SSLHandshakeException(javax.net.ssl.SSLHandshakeException) ConnectTimeoutException(org.apache.http.conn.ConnectTimeoutException)

Example 57 with ConnectTimeoutException

use of org.apache.http.conn.ConnectTimeoutException in project AndroidComponent by funnyzhaov.

the class ExceptionHandle method handleException.

/**
 * 异常的处理
 */
@NonNull
public static Throwable handleException(Throwable e) {
    ResponseThrowable ex;
    if (e instanceof HttpException) {
        HttpException httpException = (HttpException) e;
        ex = new ResponseThrowable(e, ERROR.HTTP_ERROR);
        switch(httpException.code()) {
            case UNAUTHORIZED:
            case FORBIDDEN:
            case NOT_FOUND:
            case REQUEST_TIMEOUT:
            case GATEWAY_TIMEOUT:
            case INTERNAL_SERVER_ERROR:
            case BAD_GATEWAY:
            case SERVICE_UNAVAILABLE:
            default:
                ex.message = "网络错误";
                break;
        }
        return ex;
    } else if (e instanceof ServerException) {
        ServerException resultException = (ServerException) e;
        ex = new ResponseThrowable(resultException, resultException.status);
        ex.message = resultException.message;
        return ex;
    } else if (e instanceof JsonParseException || e instanceof JSONException || e instanceof ParseException) {
        ex = new ResponseThrowable(e, ERROR.PARSE_ERROR);
        ex.message = "解析错误";
        return ex;
    } else if (e instanceof ConnectException) {
        ex = new ResponseThrowable(e, ERROR.NETWORD_ERROR);
        ex.message = "连接失败";
        return ex;
    } else if (e instanceof javax.net.ssl.SSLHandshakeException) {
        ex = new ResponseThrowable(e, ERROR.SSL_ERROR);
        ex.message = "证书验证失败";
        return ex;
    } else if (e instanceof ConnectTimeoutException) {
        ex = new ResponseThrowable(e, ERROR.TIMEOUT_ERROR);
        ex.message = "连接超时";
        return ex;
    } else if (e instanceof java.net.SocketTimeoutException) {
        ex = new ResponseThrowable(e, ERROR.TIMEOUT_ERROR);
        ex.message = "连接超时";
        return ex;
    } else {
        ex = new ResponseThrowable(e, ERROR.UNKNOWN);
        ex.message = "未知错误";
        return ex;
    }
}
Also used : JSONException(org.json.JSONException) HttpException(retrofit2.HttpException) JsonParseException(com.google.gson.JsonParseException) ParseException(java.text.ParseException) JsonParseException(com.google.gson.JsonParseException) ConnectException(java.net.ConnectException) ConnectTimeoutException(org.apache.http.conn.ConnectTimeoutException) NonNull(android.support.annotation.NonNull)

Example 58 with ConnectTimeoutException

use of org.apache.http.conn.ConnectTimeoutException in project AndroidLife by CaMnter.

the class BasicNetwork method performRequest.

/*
     * 执行处理 Volley内的 抽象请求 Request<?>
     * 但是 HttpStack 处理后,都返回 Apache 的请求结果( HttpResponse )
     * performRequest(...) 接下来会将:Apache HttpResponse -> Volley NetworkResponse 进行转化
     */
@Override
public NetworkResponse performRequest(Request<?> request) throws VolleyError {
    // 记录下 请求开始时间
    long requestStart = SystemClock.elapsedRealtime();
    // 进入一个 循环体
    while (true) {
        // 用于保存 请求结果( 响应 )
        HttpResponse httpResponse = null;
        // 用于保存 请求结果( 响应 )的 body
        byte[] responseContents = null;
        // 用于保存 请求结果( 响应 )的 Header
        Map<String, String> responseHeaders = Collections.emptyMap();
        try {
            // Gather headers.
            Map<String, String> headers = new HashMap<String, String>();
            /*
                 * 拿出缓存 Response Header 的数据
                 * 放到 headers 内
                 * 用于此次请求
                 */
            addCacheHeaders(headers, request.getCacheEntry());
            // 调用 HttpStack 执行请求,拿到 请求结果( 响应 )
            httpResponse = mHttpStack.performRequest(request, headers);
            // 提取 状态行 信息
            StatusLine statusLine = httpResponse.getStatusLine();
            // 拿到 请求结果( 响应 )的状态码
            int statusCode = statusLine.getStatusCode();
            // 进行 Apache Header[] -> Map<String, String> 转换
            responseHeaders = convertHeaders(httpResponse.getAllHeaders());
            /*
                 * 状态码 304: Not Modified
                 */
            if (statusCode == HttpStatus.SC_NOT_MODIFIED) {
                // 获取 该请求的缓存 Entry
                Entry entry = request.getCacheEntry();
                /*
                     * 没有返回 缓存 Entry
                     *
                     * data 返回 null
                     * header 采用此次请求的 responseHeaders
                     *
                     * 封装成一个 NetworkResponse
                     */
                if (entry == null) {
                    return new NetworkResponse(HttpStatus.SC_NOT_MODIFIED, null, responseHeaders, true, SystemClock.elapsedRealtime() - requestStart);
                }
                // A HTTP 304 response does not have all header fields. We
                // have to use the header fields from the cache entry plus
                // the new ones from the response.
                // http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.3.5
                // 将此次请求 的 responseHeaders 放入 缓存 Entry 的 header 内
                entry.responseHeaders.putAll(responseHeaders);
                /*
                     * data 返回 缓存内的数据 data
                     * header 为 缓存内的 header
                     *
                     * 封装成一个 NetworkResponse
                     */
                return new NetworkResponse(HttpStatus.SC_NOT_MODIFIED, entry.data, entry.responseHeaders, true, SystemClock.elapsedRealtime() - requestStart);
            }
            /*
                 * 这里处理一些 像 状态码 204: No Content
                 * 判断 Apache HttpResponse 中 的 HttpEntity 是否存在
                 */
            if (httpResponse.getEntity() != null) {
                /*
                     * 如果 Apache HttpResponse 中 的 HttpEntity 存在
                     * 那么 执行 Apache HttpEntity -> byte[] 的转化
                     */
                responseContents = entityToBytes(httpResponse.getEntity());
            } else {
                // Add 0 byte response as a way of honestly representing a
                // no-content request.
                /*
                     * 如果 Apache HttpResponse 中 的 HttpEntity 存在
                     * 为了不让 responseContents 不为 null,只能创建一个 byte[0]
                     */
                responseContents = new byte[0];
            }
            // if the request is slow, log it.
            /*
                 * 拿到 当前的时间,和刚才请求执行前记录的时间
                 * 去计算 这个请求的运行时间 = 当前的时间 - 请求执行前记录的时间
                 */
            long requestLifetime = SystemClock.elapsedRealtime() - requestStart;
            // 判断 请求时长是否在 3000ms 以上。是的话,打印 log
            logSlowRequests(requestLifetime, request, responseContents, statusLine);
            /*
                 * 200-299 用于表示请求成功。
                 */
            if (statusCode < 200 || statusCode > 299) {
                throw new IOException();
            }
            /*
                 * statusCode:状态码
                 * responseContents:请求结果( 响应 ) content
                 * responseHeaders:请求结果( 响应 ) header
                 * notModified:false
                 * SystemClock.elapsedRealtime() - requestStart: 请求时长
                 *
                 * 封装成一个 NetworkResponse,并且返回
                 */
            return new NetworkResponse(statusCode, responseContents, responseHeaders, false, SystemClock.elapsedRealtime() - requestStart);
        } catch (SocketTimeoutException e) {
            // 尝试 重试,这里只是累加 实际超时时间而已
            attemptRetryOnException("socket", request, new TimeoutError());
        } catch (ConnectTimeoutException e) {
            // 尝试 重试,这里只是累加 实际超时时间而已
            attemptRetryOnException("connection", request, new TimeoutError());
        } catch (MalformedURLException e) {
            throw new RuntimeException("Bad URL " + request.getUrl(), e);
        } catch (IOException e) {
            int statusCode;
            // 如果 没有 请求结果( 响应 ),判断为 网络错误
            if (httpResponse != null) {
                statusCode = httpResponse.getStatusLine().getStatusCode();
            } else {
                throw new NoConnectionError(e);
            }
            VolleyLog.e("Unexpected response code %d for %s", statusCode, request.getUrl());
            NetworkResponse networkResponse;
            // 状态码 204: No Content
            if (responseContents != null) {
                networkResponse = new NetworkResponse(statusCode, responseContents, responseHeaders, false, SystemClock.elapsedRealtime() - requestStart);
                // 状态码 401( Unauthorized )、 403( Forbidden )
                if (statusCode == HttpStatus.SC_UNAUTHORIZED || statusCode == HttpStatus.SC_FORBIDDEN) {
                    // 尝试 重试,这里只是累加 实际超时时间而已
                    attemptRetryOnException("auth", request, new AuthFailureError(networkResponse));
                } else if (statusCode >= 400 && statusCode <= 499) {
                    // Don't retry other client errors.
                    throw new ClientError(networkResponse);
                } else if (statusCode >= 500 && statusCode <= 599) {
                    if (request.shouldRetryServerErrors()) {
                        // 尝试 重试,这里只是累加 实际超时时间而已
                        attemptRetryOnException("server", request, new ServerError(networkResponse));
                    } else {
                        throw new ServerError(networkResponse);
                    }
                } else {
                    // 3xx? No reason to retry.
                    throw new ServerError(networkResponse);
                }
            } else {
                // 尝试 重试,这里只是累加 实际超时时间而已
                attemptRetryOnException("network", request, new NetworkError());
            }
        }
    }
}
Also used : MalformedURLException(java.net.MalformedURLException) HashMap(java.util.HashMap) ServerError(com.android.volley.ServerError) HttpResponse(org.apache.http.HttpResponse) AuthFailureError(com.android.volley.AuthFailureError) NetworkError(com.android.volley.NetworkError) NoConnectionError(com.android.volley.NoConnectionError) IOException(java.io.IOException) TimeoutError(com.android.volley.TimeoutError) StatusLine(org.apache.http.StatusLine) Entry(com.android.volley.Cache.Entry) SocketTimeoutException(java.net.SocketTimeoutException) NetworkResponse(com.android.volley.NetworkResponse) ClientError(com.android.volley.ClientError) ConnectTimeoutException(org.apache.http.conn.ConnectTimeoutException)

Example 59 with ConnectTimeoutException

use of org.apache.http.conn.ConnectTimeoutException in project neo-java by coranos.

the class TestRpcServerUtil method getResponse.

/**
 * returns the response from the RPC server.
 *
 * @param controller
 *            the controller to use.
 * @param uri
 *            the uri to send.
 * @param rpcVersion
 *            the version to send.
 * @param params
 *            the parameters to send.
 * @param method
 *            the method to call.
 * @return the response from the RPC server.
 */
public static String getResponse(final LocalControllerNode controller, final String uri, final String rpcVersion, final JSONArray params, final String method) {
    final String actualStrRaw;
    try {
        final JSONObject inputJson = createInputJson(rpcVersion, method, params);
        final String coreRpcNode = "http://localhost:" + controller.getLocalNodeData().getRpcPort() + uri;
        final StringEntity input = new StringEntity(inputJson.toString(), ContentType.APPLICATION_JSON);
        final HttpPost post = new HttpPost(coreRpcNode);
        final RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(TIMEOUT_MILLIS).setConnectTimeout(TIMEOUT_MILLIS).setConnectionRequestTimeout(TIMEOUT_MILLIS).build();
        post.setConfig(requestConfig);
        post.setEntity(input);
        final CloseableHttpClient client = HttpClients.createDefault();
        final String responseStr;
        try {
            final CloseableHttpResponse response = client.execute(post);
            logDebugStatus(response);
            final HttpEntity entity = response.getEntity();
            responseStr = EntityUtils.toString(entity);
        } catch (final ConnectTimeoutException | SocketTimeoutException | NoHttpResponseException | SocketException e) {
            throw new RuntimeException(CONNECTION_EXCEPTION, e);
        }
        try {
            final JSONObject responseJson = new JSONObject(responseStr);
            actualStrRaw = responseJson.toString(2);
        } catch (final JSONException e) {
            throw new RuntimeException("cannot parse text \"" + responseStr + "\"", e);
        }
    } catch (final Exception e) {
        throw new RuntimeException(e);
    }
    return actualStrRaw;
}
Also used : NoHttpResponseException(org.apache.http.NoHttpResponseException) HttpPost(org.apache.http.client.methods.HttpPost) RequestConfig(org.apache.http.client.config.RequestConfig) CloseableHttpClient(org.apache.http.impl.client.CloseableHttpClient) SocketException(java.net.SocketException) HttpEntity(org.apache.http.HttpEntity) JSONException(org.json.JSONException) NoHttpResponseException(org.apache.http.NoHttpResponseException) SocketException(java.net.SocketException) JSONException(org.json.JSONException) ConnectTimeoutException(org.apache.http.conn.ConnectTimeoutException) SocketTimeoutException(java.net.SocketTimeoutException) StringEntity(org.apache.http.entity.StringEntity) SocketTimeoutException(java.net.SocketTimeoutException) JSONObject(org.json.JSONObject) CloseableHttpResponse(org.apache.http.client.methods.CloseableHttpResponse) ConnectTimeoutException(org.apache.http.conn.ConnectTimeoutException)

Example 60 with ConnectTimeoutException

use of org.apache.http.conn.ConnectTimeoutException in project neo-java by coranos.

the class RpcClientUtil method post.

/**
 * posts a request.
 *
 * @param timeoutMillis
 *            the time to wait, in milliseconds. (used for SocketTimeout,
 *            ConnectTimeout, and ConnectionRequestTimeout)
 * @param rpcNode
 *            the RPC node to use.
 * @param silentErrors
 *            if false, log the error to LOG.error().
 * @param inputJson
 *            the input JSON to use.
 * @return the response, or null if an error occurs due to a timeout.
 */
public static JSONObject post(final long timeoutMillis, final String rpcNode, final boolean silentErrors, final JSONObject inputJson) {
    LOG.debug("inputJson:{}", inputJson);
    final StringEntity input = new StringEntity(inputJson.toString(), ContentType.APPLICATION_JSON);
    final HttpPost post = new HttpPost(rpcNode);
    final RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout((int) timeoutMillis).setConnectTimeout((int) timeoutMillis).setConnectionRequestTimeout((int) timeoutMillis).build();
    post.setConfig(requestConfig);
    post.setEntity(input);
    final CloseableHttpClient client = HttpClients.createDefault();
    final String str;
    try {
        final CloseableHttpResponse response = client.execute(post);
        LOG.debug("status:{}", response.getStatusLine());
        final HttpEntity entity = response.getEntity();
        str = EntityUtils.toString(entity);
    } catch (final ConnectTimeoutException | SocketTimeoutException | NoHttpResponseException | SocketException e) {
        if (!silentErrors) {
            LOG.error("post {} {} connection error:{}", rpcNode, inputJson, e.getMessage());
        }
        return null;
    } catch (final IOException e) {
        throw new RuntimeException(e);
    }
    if (!str.startsWith("{")) {
        if (!silentErrors) {
            LOG.error("post {} {} json error:\"{}\"", rpcNode, inputJson, str);
        }
        return null;
    }
    final JSONObject outputJson = new JSONObject(str);
    LOG.debug("outputJson:{}", outputJson.toString(2));
    return outputJson;
}
Also used : NoHttpResponseException(org.apache.http.NoHttpResponseException) HttpPost(org.apache.http.client.methods.HttpPost) RequestConfig(org.apache.http.client.config.RequestConfig) CloseableHttpClient(org.apache.http.impl.client.CloseableHttpClient) SocketException(java.net.SocketException) HttpEntity(org.apache.http.HttpEntity) IOException(java.io.IOException) StringEntity(org.apache.http.entity.StringEntity) SocketTimeoutException(java.net.SocketTimeoutException) JSONObject(org.json.JSONObject) CloseableHttpResponse(org.apache.http.client.methods.CloseableHttpResponse) ConnectTimeoutException(org.apache.http.conn.ConnectTimeoutException)

Aggregations

ConnectTimeoutException (org.apache.http.conn.ConnectTimeoutException)69 SocketTimeoutException (java.net.SocketTimeoutException)38 IOException (java.io.IOException)32 HttpResponse (org.apache.http.HttpResponse)18 HashMap (java.util.HashMap)14 SocketException (java.net.SocketException)13 StatusLine (org.apache.http.StatusLine)13 MalformedURLException (java.net.MalformedURLException)11 NoHttpResponseException (org.apache.http.NoHttpResponseException)11 TimeoutError (com.android.volley.TimeoutError)10 HttpPost (org.apache.http.client.methods.HttpPost)10 AuthFailureError (com.android.volley.AuthFailureError)9 NetworkError (com.android.volley.NetworkError)9 NetworkResponse (com.android.volley.NetworkResponse)9 NoConnectionError (com.android.volley.NoConnectionError)9 ServerError (com.android.volley.ServerError)9 ConnectException (java.net.ConnectException)9 DefaultHttpClient (org.apache.http.impl.client.DefaultHttpClient)9 HttpEntity (org.apache.http.HttpEntity)8 UnknownHostException (java.net.UnknownHostException)7