Search in sources :

Example 96 with ConnectTimeoutException

use of org.apache.http.conn.ConnectTimeoutException in project lavaplayer by sedmelluq.

the class ExtendedConnectionOperator method connectWithDestination.

private boolean connectWithDestination(ConnectionSocketFactory socketFactory, HttpContext context, SocketConfig socketConfig, HttpHost host, InetSocketAddress localAddress, int connectTimeout, ManagedHttpClientConnection connection, InetSocketAddress remoteAddress, InetAddress[] addresses, boolean last) throws IOException {
    Socket socket = socketFactory.createSocket(context);
    configureSocket(socket, socketConfig);
    try {
        socket = socketFactory.connectSocket(connectTimeout, socket, host, remoteAddress, localAddress, context);
        connection.bind(socket);
        return true;
    } catch (final SocketTimeoutException ex) {
        if (last) {
            throw new ConnectTimeoutException(ex, host, addresses);
        }
    } catch (final ConnectException ex) {
        if (last) {
            final String msg = ex.getMessage();
            throw "Connection timed out".equals(msg) ? new ConnectTimeoutException(ex, host, addresses) : new HttpHostConnectException(ex, host, addresses);
        }
    } catch (final NoRouteToHostException ex) {
        if (last) {
            throw ex;
        }
    }
    return false;
}
Also used : SocketTimeoutException(java.net.SocketTimeoutException) HttpHostConnectException(org.apache.http.conn.HttpHostConnectException) NoRouteToHostException(java.net.NoRouteToHostException) Socket(java.net.Socket) ConnectTimeoutException(org.apache.http.conn.ConnectTimeoutException) HttpHostConnectException(org.apache.http.conn.HttpHostConnectException) ConnectException(java.net.ConnectException)

Example 97 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 98 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 99 with ConnectTimeoutException

use of org.apache.http.conn.ConnectTimeoutException in project xian by happyyangyuan.

the class ApacheHttpClient method post.

@Override
public String post(String body) throws ConnectTimeoutException, SocketTimeoutException {
    /*
         * LOG.info(String.format(
         * "httpClient获取到的header: %s  ;   httpClient获取到的body:%s ", headers,
         * body));
         */
    if (client == null) {
        return INIT_FAIL;
    }
    HttpPost httpPost = new HttpPost(url);
    httpPost.setProtocolVersion(HttpVersion.HTTP_1_1);
    if (headers != null) {
        for (Map.Entry<String, String> entry : headers.entrySet()) {
            httpPost.setHeader(entry.getKey(), entry.getValue());
        }
    }
    String responseContent;
    try {
        StringEntity entity = new StringEntity(body == null ? "" : body, "utf-8");
        entity.setContentEncoding("utf-8");
        entity.setContentType("application/json");
        httpPost.setEntity(entity);
        httpPost.setConfig(requestConfig);
        HttpResponse httpResponse = client.execute(httpPost);
        responseContent = EntityUtils.toString(httpResponse.getEntity(), "utf-8");
    } catch (ConnectTimeoutException | SocketTimeoutException connectOrReadTimeout) {
        throw connectOrReadTimeout;
    } catch (Exception e) {
        throw new RuntimeException(e);
    } finally {
        httpPost.releaseConnection();
    }
    return responseContent;
}
Also used : HttpPost(org.apache.http.client.methods.HttpPost) StringEntity(org.apache.http.entity.StringEntity) SocketTimeoutException(java.net.SocketTimeoutException) Map(java.util.Map) IOException(java.io.IOException) ConnectTimeoutException(org.apache.http.conn.ConnectTimeoutException) SocketTimeoutException(java.net.SocketTimeoutException) ConnectTimeoutException(org.apache.http.conn.ConnectTimeoutException)

Example 100 with ConnectTimeoutException

use of org.apache.http.conn.ConnectTimeoutException in project xian by happyyangyuan.

the class ApacheHttpClient method get.

@Override
public String get() throws ConnectTimeoutException, SocketTimeoutException {
    if (client == null) {
        return INIT_FAIL;
    }
    HttpGet httpGet = new HttpGet(url);
    httpGet.setProtocolVersion(HttpVersion.HTTP_1_1);
    if (headers != null) {
        for (Map.Entry<String, String> entry : headers.entrySet()) {
            httpGet.setHeader(entry.getKey(), entry.getValue());
        }
    }
    String responseContent;
    try {
        httpGet.setConfig(requestConfig);
        HttpResponse httpResponse = client.execute(httpGet);
        responseContent = EntityUtils.toString(httpResponse.getEntity(), "UTF-8");
    } catch (ConnectTimeoutException | SocketTimeoutException connectOrReadTimeout) {
        throw connectOrReadTimeout;
    } catch (Exception e) {
        throw new RuntimeException(e);
    } finally {
        httpGet.releaseConnection();
    }
    return responseContent;
}
Also used : SocketTimeoutException(java.net.SocketTimeoutException) HttpGet(org.apache.http.client.methods.HttpGet) Map(java.util.Map) IOException(java.io.IOException) ConnectTimeoutException(org.apache.http.conn.ConnectTimeoutException) SocketTimeoutException(java.net.SocketTimeoutException) ConnectTimeoutException(org.apache.http.conn.ConnectTimeoutException)

Aggregations

ConnectTimeoutException (org.apache.http.conn.ConnectTimeoutException)136 SocketTimeoutException (java.net.SocketTimeoutException)72 IOException (java.io.IOException)62 HttpResponse (org.apache.http.HttpResponse)28 HttpPost (org.apache.http.client.methods.HttpPost)21 HttpHostConnectException (org.apache.http.conn.HttpHostConnectException)21 ConnectException (java.net.ConnectException)18 HttpEntity (org.apache.http.HttpEntity)17 HttpClient (org.apache.http.client.HttpClient)17 Test (org.junit.Test)17 SocketException (java.net.SocketException)16 UnknownHostException (java.net.UnknownHostException)16 HashMap (java.util.HashMap)16 NoHttpResponseException (org.apache.http.NoHttpResponseException)16 StatusLine (org.apache.http.StatusLine)16 ClientProtocolException (org.apache.http.client.ClientProtocolException)16 HttpGet (org.apache.http.client.methods.HttpGet)15 DefaultHttpClient (org.apache.http.impl.client.DefaultHttpClient)14 CloseableHttpResponse (org.apache.http.client.methods.CloseableHttpResponse)13 MalformedURLException (java.net.MalformedURLException)11