Search in sources :

Example 61 with ConnectTimeoutException

use of org.apache.http.conn.ConnectTimeoutException in project 91Pop by DanteAndroid.

the class ApiException method handleException.

public static ApiException handleException(Throwable e) {
    // 使用RxCache之后返回的是包裹的CompositeException,一般包含2个异常,rxcache异常和原本的异常
    Logger.t(TAG).d("开始解析错误------");
    if (e instanceof CompositeException) {
        CompositeException compositeException = (CompositeException) e;
        for (Throwable throwable : compositeException.getExceptions()) {
            if (!(throwable instanceof RxCacheException)) {
                e = throwable;
                Logger.t(TAG).d("其他异常:" + throwable.getMessage());
            } else {
                Logger.t(TAG).d("RxCache 异常");
            }
        }
    }
    ApiException ex;
    if (e instanceof HttpException) {
        HttpException httpException = (HttpException) e;
        ex = new ApiException(httpException, httpException.code());
        ex.message = httpException.getMessage();
        return ex;
    } else if (e instanceof JsonParseException || e instanceof JSONException || e instanceof JsonSerializer || e instanceof NotSerializableException || e instanceof ParseException) {
        ex = new ApiException(e, Error.PARSE_ERROR);
        ex.message = "数据解析错误";
        return ex;
    } else if (e instanceof ClassCastException) {
        ex = new ApiException(e, Error.CAST_ERROR);
        ex.message = "类型转换错误";
        return ex;
    } else if (e instanceof ConnectException) {
        ex = new ApiException(e, Error.NETWORD_ERROR);
        ex.message = "连接失败";
        return ex;
    } else if (e instanceof javax.net.ssl.SSLHandshakeException) {
        ex = new ApiException(e, Error.SSL_ERROR);
        ex.message = "证书验证失败";
        return ex;
    } else if (e instanceof ConnectTimeoutException) {
        ex = new ApiException(e, Error.TIMEOUT_ERROR);
        ex.message = "网络连接超时";
        return ex;
    } else if (e instanceof java.net.SocketTimeoutException) {
        ex = new ApiException(e, Error.TIMEOUT_ERROR);
        ex.message = "网络连接超时";
        return ex;
    } else if (e instanceof UnknownHostException) {
        ex = new ApiException(e, Error.UNKNOWNHOST_ERROR);
        ex.message = "无法解析该域名";
        return ex;
    } else if (e instanceof NullPointerException) {
        ex = new ApiException(e, Error.NULLPOINTER_EXCEPTION);
        ex.message = "NullPointerException";
        return ex;
    } else if (e instanceof VideoException) {
        ex = new ApiException(e, Error.PARSE_VIDEO_URL_ERROR);
        ex.message = e.getMessage();
        return ex;
    } else if (e instanceof FavoriteException) {
        ex = new ApiException(e, Error.FAVORITE_VIDEO_ERROR);
        ex.message = e.getMessage();
        return ex;
    } else if (e instanceof DaoException) {
        ex = new ApiException(e, Error.GREEN_DAO_ERROR);
        ex.message = "数据库错误";
        return ex;
    } else if (e instanceof MessageException) {
        ex = new ApiException(e, Error.COMMON_MESSAGE_ERROR);
        ex.message = e.getMessage();
        return ex;
    } else {
        ex = new ApiException(e, Error.UNKNOWN);
        ex.message = "未知错误:" + e.getMessage();
        return ex;
    }
}
Also used : UnknownHostException(java.net.UnknownHostException) CompositeException(io.reactivex.exceptions.CompositeException) RxCacheException(io.rx_cache2.RxCacheException) JSONException(org.json.JSONException) JsonSerializer(com.google.gson.JsonSerializer) JsonParseException(com.google.gson.JsonParseException) DaoException(org.greenrobot.greendao.DaoException) NotSerializableException(java.io.NotSerializableException) HttpException(retrofit2.HttpException) JsonParseException(com.google.gson.JsonParseException) ParseException(android.net.ParseException) ConnectException(java.net.ConnectException) ConnectTimeoutException(org.apache.http.conn.ConnectTimeoutException)

Example 62 with ConnectTimeoutException

use of org.apache.http.conn.ConnectTimeoutException in project flink by apache.

the class KinesisProxyTest method testIsRecoverableExceptionWithConnectError.

@Test
public void testIsRecoverableExceptionWithConnectError() throws UnknownHostException {
    Properties kinesisConsumerConfig = new Properties();
    kinesisConsumerConfig.setProperty(ConsumerConfigConstants.AWS_REGION, "us-east-1");
    KinesisProxy kinesisProxy = new KinesisProxy(kinesisConsumerConfig);
    final SdkClientException ex = new SdkClientException("Unable to execute HTTP request", new ConnectTimeoutException(new java.net.SocketTimeoutException("connect timed out"), new HttpHost("kinesis.us-east-1.amazonaws.com", 443), InetAddress.getByAddress("kinesis.us-east-1.amazonaws.com", new byte[] { 3, 91, (byte) 171, (byte) 253 })));
    assertTrue(kinesisProxy.isRecoverableSdkClientException(ex));
}
Also used : SdkClientException(com.amazonaws.SdkClientException) HttpHost(org.apache.http.HttpHost) Properties(java.util.Properties) ConnectTimeoutException(org.apache.http.conn.ConnectTimeoutException) Test(org.junit.Test)

Example 63 with ConnectTimeoutException

use of org.apache.http.conn.ConnectTimeoutException in project new-cloud by xie-summer.

the class HttpUtils method uploadFile.

/**
 * @param url
 * @param params
 * @param uploadMap
 * @param fileNameMap
 * @param encode
 * @return
 */
public static HttpResult uploadFile(String url, Map<String, String> params, Map<String, byte[]> uploadMap, Map<String, String> fileNameMap, String encode, int timeout) {
    /**
     * DefaultHttpClient client = new DefaultHttpClient();
     * client.getParams().setIntParameter("http.socket.timeout",
     * LONG_TIMEOUT); client.getParams().setBooleanParameter(
     * "http.protocol.expect-continue", false);
     * client.getParams().setIntParameter("http.connection.timeout",
     * CONNECTION_TIMEOUT);
     */
    CookieStore cookieStore = getCookieStore(null);
    CloseableHttpClient client = getHttpClient(CONNECTION_TIMEOUT, timeout, cookieStore);
    MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create().setCharset(Charset.forName(encode));
    HttpPost request = new HttpPost(url);
    // MultipartEntity reqEntity = new MultipartEntity();
    for (String input : uploadMap.keySet()) {
        ByteArrayBody isb = new ByteArrayBody(uploadMap.get(input), fileNameMap.get(input));
        multipartEntityBuilder.addPart(input, isb);
    }
    try {
        if (params != null && !params.isEmpty()) {
            for (String key : params.keySet()) {
                multipartEntityBuilder.addTextBody(key, params.get(key), ContentType.create("text/plain", Charset.forName(encode)));
            }
        }
        request.setEntity(multipartEntityBuilder.build());
        List<Cookie> reqcookie = cookieStore.getCookies();
        CloseableHttpResponse response = client.execute(request);
        try {
            String result = "";
            HttpEntity entity = getEntity(response);
            if (entity != null) {
                result = EntityUtils.toString(entity, encode);
            }
            if (isSuccess(response)) {
                HttpResult ret = HttpResult.getSuccessReturn(result);
                addHeader(ret, response);
                List<Cookie> cookies = cookieStore.getCookies();
                addCookie(ret, cookies, reqcookie);
                return ret;
            } else {
                int statusCode = response.getStatusLine().getStatusCode();
                String msg = "httpStatus:" + statusCode + response.getStatusLine().getReasonPhrase() + ", Header: ";
                Header[] headers = response.getAllHeaders();
                for (Header header : headers) {
                    msg += header.getName() + ":" + header.getValue();
                }
                request.abort();
                DB_LOGGER.error("ERROR HttpUtils:" + msg + request.getURI());
                return HttpResult.getFailure("httpStatus:" + response.getStatusLine().getStatusCode(), statusCode, result);
            }
        } finally {
            response.close();
        }
    } catch (HttpHostConnectException e) {
        request.abort();
        DB_LOGGER.error(request.getURI() + ":" + LoggerUtils.getExceptionTrace(e, 30));
        return HttpResult.getFailure(request.getURI() + " exception:" + e.getClass().getCanonicalName(), HTTP_STATUSCODE_HTTP_HOST_CONNECT_EXCEPTION);
    } catch (ConnectTimeoutException e) {
        request.abort();
        DB_LOGGER.error(request.getURI() + ":" + LoggerUtils.getExceptionTrace(e, 30));
        return HttpResult.getFailure(request.getURI() + " exception:" + e.getClass().getCanonicalName(), HTTP_STATUSCODE_CONNECT_TIMEOUT_EXCEPTION);
    } catch (SocketTimeoutException e) {
        request.abort();
        DB_LOGGER.error(request.getURI() + ":" + LoggerUtils.getExceptionTrace(e, 30));
        return HttpResult.getFailure(request.getURI() + " exception:" + e.getClass().getCanonicalName(), HTTP_STATUSCODE_SOCKET_TIMEOUT_EXCEPTION);
    } catch (Exception e) {
        request.abort();
        DB_LOGGER.error(request.getURI() + ":" + LoggerUtils.getExceptionTrace(e, 100));
        return HttpResult.getFailure(request.getURI() + " exception:" + e.getClass().getCanonicalName(), EXCEPTION_HTTP_STATUSCODE);
    }
}
Also used : Cookie(org.apache.http.cookie.Cookie) BasicClientCookie(org.apache.http.impl.cookie.BasicClientCookie) CloseableHttpClient(org.apache.http.impl.client.CloseableHttpClient) HttpPost(org.apache.http.client.methods.HttpPost) MultipartEntityBuilder(org.apache.http.entity.mime.MultipartEntityBuilder) ByteArrayBody(org.apache.http.entity.mime.content.ByteArrayBody) HttpHostConnectException(org.apache.http.conn.HttpHostConnectException) KeyManagementException(java.security.KeyManagementException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) ConnectTimeoutException(org.apache.http.conn.ConnectTimeoutException) SocketTimeoutException(java.net.SocketTimeoutException) CookieStore(org.apache.http.client.CookieStore) BasicCookieStore(org.apache.http.impl.client.BasicCookieStore) SocketTimeoutException(java.net.SocketTimeoutException) CloseableHttpResponse(org.apache.http.client.methods.CloseableHttpResponse) HttpHostConnectException(org.apache.http.conn.HttpHostConnectException) ConnectTimeoutException(org.apache.http.conn.ConnectTimeoutException)

Example 64 with ConnectTimeoutException

use of org.apache.http.conn.ConnectTimeoutException in project NetDiscovery 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 65 with ConnectTimeoutException

use of org.apache.http.conn.ConnectTimeoutException in project saga-android by AnandChowdhary.

the class BasicNetwork method performRequest.

@Override
public NetworkResponse performRequest(Request<?> request) throws VolleyError {
    long requestStart = SystemClock.elapsedRealtime();
    while (true) {
        HttpResponse httpResponse = null;
        byte[] responseContents = null;
        Map<String, String> responseHeaders = new HashMap<String, String>();
        try {
            // Gather headers.
            Map<String, String> headers = new HashMap<String, String>();
            addCacheHeaders(headers, request.getCacheEntry());
            httpResponse = mHttpStack.performRequest(request, headers);
            StatusLine statusLine = httpResponse.getStatusLine();
            int statusCode = statusLine.getStatusCode();
            responseHeaders = convertHeaders(httpResponse.getAllHeaders());
            // Handle cache validation.
            if (statusCode == HttpStatus.SC_NOT_MODIFIED) {
                return new NetworkResponse(HttpStatus.SC_NOT_MODIFIED, request.getCacheEntry().data, responseHeaders, true);
            }
            responseContents = entityToBytes(httpResponse.getEntity());
            // if the request is slow, log it.
            long requestLifetime = SystemClock.elapsedRealtime() - requestStart;
            logSlowRequests(requestLifetime, request, responseContents, statusLine);
            if (statusCode != HttpStatus.SC_OK && statusCode != HttpStatus.SC_NO_CONTENT) {
                throw new IOException();
            }
            return new NetworkResponse(statusCode, responseContents, responseHeaders, false);
        } 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 = 0;
            NetworkResponse networkResponse = null;
            if (httpResponse != null) {
                statusCode = httpResponse.getStatusLine().getStatusCode();
            } else {
                if (request.getCacheEntry() != null && request.getCacheEntry().data != null) {
                    return new NetworkResponse(HttpStatus.SC_NOT_MODIFIED, request.getCacheEntry().data, responseHeaders, true);
                } else {
                    throw new NoConnectionError(e);
                }
            }
            VolleyLog.e("Unexpected response code %d for %s", statusCode, request.getUrl());
            if (responseContents != null) {
                networkResponse = new NetworkResponse(statusCode, responseContents, responseHeaders, false);
                if (statusCode == HttpStatus.SC_UNAUTHORIZED || statusCode == HttpStatus.SC_FORBIDDEN) {
                    attemptRetryOnException("auth", request, new AuthFailureError(networkResponse));
                } else {
                    // TODO: Only throw ServerError for 5xx status codes.
                    throw new ServerError(networkResponse);
                }
            } else {
                throw new NetworkError(networkResponse);
            }
        }
    }
}
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) SocketTimeoutException(java.net.SocketTimeoutException) NetworkResponse(com.android.volley.NetworkResponse) 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