Search in sources :

Example 86 with ConnectTimeoutException

use of org.apache.http.conn.ConnectTimeoutException in project Douya by DreaminginCodeZH.

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 = Collections.emptyMap();
        try {
            // Gather headers.
            Map<String, String> headers = new HashMap<>();
            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) {
                Cache.Entry entry = request.getCacheEntry();
                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
                entry.responseHeaders.putAll(responseHeaders);
                return new NetworkResponse(HttpStatus.SC_NOT_MODIFIED, entry.data, entry.responseHeaders, true, SystemClock.elapsedRealtime() - requestStart);
            }
            // Some responses such as 204s do not have content.  We must check.
            if (httpResponse.getEntity() != null) {
                responseContents = entityToBytes(httpResponse.getEntity());
            } else {
                // Add 0 byte response as a way of honestly representing a
                // no-content request.
                responseContents = new byte[0];
            }
            // if the request is slow, log it.
            long requestLifetime = SystemClock.elapsedRealtime() - requestStart;
            logSlowRequests(requestLifetime, request, responseContents, statusLine);
            if (statusCode < 200 || statusCode > 299) {
                throw new IOException();
            }
            return new NetworkResponse(statusCode, responseContents, responseHeaders, false, SystemClock.elapsedRealtime() - requestStart);
        } catch (MalformedURLException e) {
            throw new RuntimeException("Bad URL " + request.getUrl(), e);
        } catch (SocketTimeoutException e) {
            attemptRetryOnException("socket-timeout", request, new TimeoutError());
        } catch (ConnectTimeoutException e) {
            attemptRetryOnException("connection-timeout", request, new TimeoutError());
        } catch (IOException e) {
            int statusCode;
            if (httpResponse != null) {
                statusCode = httpResponse.getStatusLine().getStatusCode();
            } else {
                // PATCH: Let RetryPolicy decide whether the request should be aborted.
                attemptRetryOnException("no-connection", request, new NoConnectionError(e));
                continue;
            }
            VolleyLog.e("Unexpected response code %d for %s", statusCode, request.getUrl());
            if (responseContents != null) {
                NetworkResponse networkResponse = new NetworkResponse(statusCode, responseContents, responseHeaders, false, SystemClock.elapsedRealtime() - requestStart);
                if (statusCode == HttpStatus.SC_UNAUTHORIZED || statusCode == HttpStatus.SC_FORBIDDEN) {
                    attemptRetryOnException("auth", request, new AuthFailureError(networkResponse));
                } else {
                    // PATCH: Let RetryPolicy decide whether the request should be aborted.
                    // TODO: Only throw ServerError for 5xx status codes.
                    attemptRetryOnException("server", request, new ServerError(networkResponse));
                }
            } else {
                // PATCH: Let RetryPolicy decide whether the request should be aborted.
                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) SocketTimeoutException(java.net.SocketTimeoutException) NetworkResponse(com.android.volley.NetworkResponse) Cache(com.android.volley.Cache) ConnectTimeoutException(org.apache.http.conn.ConnectTimeoutException)

Example 87 with ConnectTimeoutException

use of org.apache.http.conn.ConnectTimeoutException in project XobotOS by xamarin.

the class PlainSocketFactory method connectSocket.

// non-javadoc, see interface org.apache.http.conn.SocketFactory
public Socket connectSocket(Socket sock, String host, int port, InetAddress localAddress, int localPort, HttpParams params) throws IOException {
    if (host == null) {
        throw new IllegalArgumentException("Target host may not be null.");
    }
    if (params == null) {
        throw new IllegalArgumentException("Parameters may not be null.");
    }
    if (sock == null)
        sock = createSocket();
    if ((localAddress != null) || (localPort > 0)) {
        // we need to bind explicitly
        if (localPort < 0)
            // indicates "any"
            localPort = 0;
        InetSocketAddress isa = new InetSocketAddress(localAddress, localPort);
        sock.bind(isa);
    }
    int timeout = HttpConnectionParams.getConnectionTimeout(params);
    InetSocketAddress remoteAddress;
    if (this.nameResolver != null) {
        remoteAddress = new InetSocketAddress(this.nameResolver.resolve(host), port);
    } else {
        remoteAddress = new InetSocketAddress(host, port);
    }
    try {
        sock.connect(remoteAddress, timeout);
    } catch (SocketTimeoutException ex) {
        throw new ConnectTimeoutException("Connect to " + remoteAddress + " timed out");
    }
    return sock;
}
Also used : SocketTimeoutException(java.net.SocketTimeoutException) InetSocketAddress(java.net.InetSocketAddress) ConnectTimeoutException(org.apache.http.conn.ConnectTimeoutException)

Example 88 with ConnectTimeoutException

use of org.apache.http.conn.ConnectTimeoutException in project XobotOS by xamarin.

the class DefaultClientConnectionOperator method openConnection.

// non-javadoc, see interface ClientConnectionOperator
public void openConnection(OperatedClientConnection conn, HttpHost target, InetAddress local, HttpContext context, HttpParams params) throws IOException {
    if (conn == null) {
        throw new IllegalArgumentException("Connection must not be null.");
    }
    if (target == null) {
        throw new IllegalArgumentException("Target host must not be null.");
    }
    //@@@ is context allowed to be null?
    if (params == null) {
        throw new IllegalArgumentException("Parameters must not be null.");
    }
    if (conn.isOpen()) {
        throw new IllegalArgumentException("Connection must not be open.");
    }
    final Scheme schm = schemeRegistry.getScheme(target.getSchemeName());
    final SocketFactory sf = schm.getSocketFactory();
    final SocketFactory plain_sf;
    final LayeredSocketFactory layered_sf;
    if (sf instanceof LayeredSocketFactory) {
        plain_sf = staticPlainSocketFactory;
        layered_sf = (LayeredSocketFactory) sf;
    } else {
        plain_sf = sf;
        layered_sf = null;
    }
    InetAddress[] addresses = InetAddress.getAllByName(target.getHostName());
    for (int i = 0; i < addresses.length; ++i) {
        Socket sock = plain_sf.createSocket();
        conn.opening(sock, target);
        try {
            Socket connsock = plain_sf.connectSocket(sock, addresses[i].getHostAddress(), schm.resolvePort(target.getPort()), local, 0, params);
            if (sock != connsock) {
                sock = connsock;
                conn.opening(sock, target);
            }
            /*
                 * prepareSocket is called on the just connected
                 * socket before the creation of the layered socket to
                 * ensure that desired socket options such as
                 * TCP_NODELAY, SO_RCVTIMEO, SO_LINGER will be set
                 * before any I/O is performed on the socket. This
                 * happens in the common case as
                 * SSLSocketFactory.createSocket performs hostname
                 * verification which requires that SSL handshaking be
                 * performed.
                 */
            prepareSocket(sock, context, params);
            if (layered_sf != null) {
                Socket layeredsock = layered_sf.createSocket(sock, target.getHostName(), schm.resolvePort(target.getPort()), true);
                if (layeredsock != sock) {
                    conn.opening(layeredsock, target);
                }
                conn.openCompleted(sf.isSecure(layeredsock), params);
            } else {
                conn.openCompleted(sf.isSecure(sock), params);
            }
            break;
        // BEGIN android-changed
        //       catch SocketException to cover any kind of connect failure
        } catch (SocketException ex) {
            if (i == addresses.length - 1) {
                ConnectException cause = ex instanceof ConnectException ? (ConnectException) ex : new ConnectException(ex.getMessage(), ex);
                throw new HttpHostConnectException(target, cause);
            }
        // END android-changed
        } catch (ConnectTimeoutException ex) {
            if (i == addresses.length - 1) {
                throw ex;
            }
        }
    }
}
Also used : SocketException(java.net.SocketException) Scheme(org.apache.http.conn.scheme.Scheme) PlainSocketFactory(org.apache.http.conn.scheme.PlainSocketFactory) LayeredSocketFactory(org.apache.http.conn.scheme.LayeredSocketFactory) SocketFactory(org.apache.http.conn.scheme.SocketFactory) HttpHostConnectException(org.apache.http.conn.HttpHostConnectException) LayeredSocketFactory(org.apache.http.conn.scheme.LayeredSocketFactory) InetAddress(java.net.InetAddress) Socket(java.net.Socket) HttpHostConnectException(org.apache.http.conn.HttpHostConnectException) ConnectException(java.net.ConnectException) ConnectTimeoutException(org.apache.http.conn.ConnectTimeoutException)

Example 89 with ConnectTimeoutException

use of org.apache.http.conn.ConnectTimeoutException in project UltimateAndroid by cymcsg.

the class HttpUtils method getResponseFromPostUrl.

public static String getResponseFromPostUrl(String url, List<NameValuePair> params) throws Exception {
    String result = null;
    // 新建HttpPost对象
    HttpPost httpPost = new HttpPost(url);
    // 设置字符集
    HttpEntity entity = new UrlEncodedFormEntity(params, HTTP.UTF_8);
    // 设置参数实体
    httpPost.setEntity(entity);
    // 获取HttpClient对象
    HttpClient httpClient = new DefaultHttpClient();
    //连接超时
    httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 30000);
    //请求超时
    httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 30000);
    try {
        // 获取HttpResponse实例
        HttpResponse httpResp = httpClient.execute(httpPost);
        // 判断是够请求成功
        if (httpResp.getStatusLine().getStatusCode() == 200) {
            // 获取返回的数据
            result = EntityUtils.toString(httpResp.getEntity(), "UTF-8");
            Logs.d("HttpPost success :");
            Logs.d(result);
        } else {
            Logs.d("HttpPost failed" + "    " + httpResp.getStatusLine().getStatusCode() + "   " + EntityUtils.toString(httpResp.getEntity(), "UTF-8"));
            result = "connect_failed";
        }
    } catch (ConnectTimeoutException e) {
        result = "";
        Logs.e("HttpPost overtime:  " + "");
    } catch (Exception e) {
        e.printStackTrace();
        Logs.e(e, "");
        result = "";
    }
    return result;
}
Also used : HttpPost(org.apache.http.client.methods.HttpPost) DefaultHttpClient(org.apache.http.impl.client.DefaultHttpClient) HttpClient(org.apache.http.client.HttpClient) UrlEncodedFormEntity(org.apache.http.client.entity.UrlEncodedFormEntity) DefaultHttpClient(org.apache.http.impl.client.DefaultHttpClient) ConnectTimeoutException(org.apache.http.conn.ConnectTimeoutException) ConnectTimeoutException(org.apache.http.conn.ConnectTimeoutException)

Example 90 with ConnectTimeoutException

use of org.apache.http.conn.ConnectTimeoutException in project lucene-solr by apache.

the class CloudSolrClient method requestWithRetryOnStaleState.

/**
   * As this class doesn't watch external collections on the client side,
   * there's a chance that the request will fail due to cached stale state,
   * which means the state must be refreshed from ZK and retried.
   */
protected NamedList<Object> requestWithRetryOnStaleState(SolrRequest request, int retryCount, String collection) throws SolrServerException, IOException {
    // important to call this before you start working with the ZkStateReader
    connect();
    // build up a _stateVer_ param to pass to the server containing all of the
    // external collection state versions involved in this request, which allows
    // the server to notify us that our cached state for one or more of the external
    // collections is stale and needs to be refreshed ... this code has no impact on internal collections
    String stateVerParam = null;
    List<DocCollection> requestedCollections = null;
    boolean isCollectionRequestOfV2 = false;
    if (request instanceof V2Request) {
        isCollectionRequestOfV2 = ((V2Request) request).isPerCollectionRequest();
    }
    boolean isAdmin = ADMIN_PATHS.contains(request.getPath());
    if (collection != null && !isAdmin && !isCollectionRequestOfV2) {
        // don't do _stateVer_ checking for admin, v2 api requests
        Set<String> requestedCollectionNames = getCollectionNames(collection);
        StringBuilder stateVerParamBuilder = null;
        for (String requestedCollection : requestedCollectionNames) {
            // track the version of state we're using on the client side using the _stateVer_ param
            DocCollection coll = getDocCollection(requestedCollection, null);
            if (coll == null) {
                throw new SolrException(ErrorCode.BAD_REQUEST, "Collection not found: " + requestedCollection);
            }
            int collVer = coll.getZNodeVersion();
            if (coll.getStateFormat() > 1) {
                if (requestedCollections == null)
                    requestedCollections = new ArrayList<>(requestedCollectionNames.size());
                requestedCollections.add(coll);
                if (stateVerParamBuilder == null) {
                    stateVerParamBuilder = new StringBuilder();
                } else {
                    // hopefully pipe is not an allowed char in a collection name
                    stateVerParamBuilder.append("|");
                }
                stateVerParamBuilder.append(coll.getName()).append(":").append(collVer);
            }
        }
        if (stateVerParamBuilder != null) {
            stateVerParam = stateVerParamBuilder.toString();
        }
    }
    if (request.getParams() instanceof ModifiableSolrParams) {
        ModifiableSolrParams params = (ModifiableSolrParams) request.getParams();
        if (stateVerParam != null) {
            params.set(STATE_VERSION, stateVerParam);
        } else {
            params.remove(STATE_VERSION);
        }
    }
    // else: ??? how to set this ???
    NamedList<Object> resp = null;
    try {
        resp = sendRequest(request, collection);
        //to avoid an O(n) operation we always add STATE_VERSION to the last and try to read it from there
        Object o = resp == null || resp.size() == 0 ? null : resp.get(STATE_VERSION, resp.size() - 1);
        if (o != null && o instanceof Map) {
            //remove this because no one else needs this and tests would fail if they are comparing responses
            resp.remove(resp.size() - 1);
            Map invalidStates = (Map) o;
            for (Object invalidEntries : invalidStates.entrySet()) {
                Map.Entry e = (Map.Entry) invalidEntries;
                getDocCollection((String) e.getKey(), (Integer) e.getValue());
            }
        }
    } catch (Exception exc) {
        Throwable rootCause = SolrException.getRootCause(exc);
        // or request is v2 api and its method is not GET
        if (collection == null || isAdmin || (request instanceof V2Request && request.getMethod() != SolrRequest.METHOD.GET)) {
            if (exc instanceof SolrServerException) {
                throw (SolrServerException) exc;
            } else if (exc instanceof IOException) {
                throw (IOException) exc;
            } else if (exc instanceof RuntimeException) {
                throw (RuntimeException) exc;
            } else {
                throw new SolrServerException(rootCause);
            }
        }
        int errorCode = (rootCause instanceof SolrException) ? ((SolrException) rootCause).code() : SolrException.ErrorCode.UNKNOWN.code;
        log.error("Request to collection {} failed due to (" + errorCode + ") {}, retry? " + retryCount, collection, rootCause.toString());
        boolean wasCommError = (rootCause instanceof ConnectException || rootCause instanceof ConnectTimeoutException || rootCause instanceof NoHttpResponseException || rootCause instanceof SocketException);
        if (wasCommError) {
            // in retryExpiryTime time
            for (DocCollection ext : requestedCollections) {
                ExpiringCachedDocCollection cacheEntry = collectionStateCache.get(ext.getName());
                if (cacheEntry == null)
                    continue;
                cacheEntry.maybeStale = true;
            }
            if (retryCount < MAX_STALE_RETRIES) {
                // the state would not have been updated
                return requestWithRetryOnStaleState(request, retryCount + 1, collection);
            }
        }
        boolean stateWasStale = false;
        if (retryCount < MAX_STALE_RETRIES && requestedCollections != null && !requestedCollections.isEmpty() && SolrException.ErrorCode.getErrorCode(errorCode) == SolrException.ErrorCode.INVALID_STATE) {
            // cached state for one or more external collections was stale
            // re-issue request using updated state
            stateWasStale = true;
            // just re-read state for all of them, which is a little heavy handed but hopefully a rare occurrence
            for (DocCollection ext : requestedCollections) {
                collectionStateCache.remove(ext.getName());
            }
        }
        // with ZK just to make sure the node we're trying to hit is still part of the collection
        if (retryCount < MAX_STALE_RETRIES && !stateWasStale && requestedCollections != null && !requestedCollections.isEmpty() && wasCommError) {
            for (DocCollection ext : requestedCollections) {
                DocCollection latestStateFromZk = getDocCollection(ext.getName(), null);
                if (latestStateFromZk.getZNodeVersion() != ext.getZNodeVersion()) {
                    // looks like we couldn't reach the server because the state was stale == retry
                    stateWasStale = true;
                    // we just pulled state from ZK, so update the cache so that the retry uses it
                    collectionStateCache.put(ext.getName(), new ExpiringCachedDocCollection(latestStateFromZk));
                }
            }
        }
        if (requestedCollections != null) {
            // done with this
            requestedCollections.clear();
        }
        // if the state was stale, then we retry the request once with new state pulled from Zk
        if (stateWasStale) {
            log.warn("Re-trying request to  collection(s) " + collection + " after stale state error from server.");
            resp = requestWithRetryOnStaleState(request, retryCount + 1, collection);
        } else {
            if (exc instanceof SolrException) {
                throw exc;
            }
            if (exc instanceof SolrServerException) {
                throw (SolrServerException) exc;
            } else if (exc instanceof IOException) {
                throw (IOException) exc;
            } else {
                throw new SolrServerException(rootCause);
            }
        }
    }
    return resp;
}
Also used : SocketException(java.net.SocketException) SolrServerException(org.apache.solr.client.solrj.SolrServerException) ArrayList(java.util.ArrayList) ModifiableSolrParams(org.apache.solr.common.params.ModifiableSolrParams) DocCollection(org.apache.solr.common.cloud.DocCollection) SolrException(org.apache.solr.common.SolrException) ConnectException(java.net.ConnectException) NoHttpResponseException(org.apache.http.NoHttpResponseException) IOException(java.io.IOException) V2Request(org.apache.solr.client.solrj.request.V2Request) TimeoutException(java.util.concurrent.TimeoutException) NoHttpResponseException(org.apache.http.NoHttpResponseException) SolrServerException(org.apache.solr.client.solrj.SolrServerException) SolrException(org.apache.solr.common.SolrException) SocketException(java.net.SocketException) ConnectTimeoutException(org.apache.http.conn.ConnectTimeoutException) ConnectException(java.net.ConnectException) IOException(java.io.IOException) ExecutionException(java.util.concurrent.ExecutionException) SimpleOrderedMap(org.apache.solr.common.util.SimpleOrderedMap) Map(java.util.Map) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap) ConnectTimeoutException(org.apache.http.conn.ConnectTimeoutException)

Aggregations

ConnectTimeoutException (org.apache.http.conn.ConnectTimeoutException)153 SocketTimeoutException (java.net.SocketTimeoutException)79 IOException (java.io.IOException)67 HttpResponse (org.apache.http.HttpResponse)31 HttpHostConnectException (org.apache.http.conn.HttpHostConnectException)23 UnknownHostException (java.net.UnknownHostException)22 HttpPost (org.apache.http.client.methods.HttpPost)21 Test (org.junit.Test)21 SocketException (java.net.SocketException)19 HttpEntity (org.apache.http.HttpEntity)19 ConnectException (java.net.ConnectException)18 HashMap (java.util.HashMap)17 NoHttpResponseException (org.apache.http.NoHttpResponseException)17 StatusLine (org.apache.http.StatusLine)17 HttpClient (org.apache.http.client.HttpClient)17 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)12