Search in sources :

Example 6 with ConnectTimeoutException

use of org.apache.http.conn.ConnectTimeoutException in project 9GAG by Mixiaoxiao.

the class MxxHttpUtil method doHttpPost.

/**
	 * Op Http post request , "404error" response if failed
	 * 
	 * @param url
	 * @param map
	 *            Values to request
	 * @return
	 */
public static String doHttpPost(String url, HashMap<String, String> map) {
    HttpClient client = new DefaultHttpClient();
    HttpConnectionParams.setConnectionTimeout(client.getParams(), TIMEOUT);
    HttpConnectionParams.setSoTimeout(client.getParams(), TIMEOUT);
    ConnManagerParams.setTimeout(client.getParams(), TIMEOUT);
    HttpPost post = new HttpPost(url);
    post.setHeaders(headers);
    String result = "ERROR";
    ArrayList<BasicNameValuePair> pairList = new ArrayList<BasicNameValuePair>();
    if (map != null) {
        for (Map.Entry<String, String> entry : map.entrySet()) {
            BasicNameValuePair pair = new BasicNameValuePair(entry.getKey(), entry.getValue());
            pairList.add(pair);
        }
    }
    try {
        HttpEntity entity = new UrlEncodedFormEntity(pairList, "UTF-8");
        post.setEntity(entity);
        HttpResponse response = client.execute(post);
        if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
            result = EntityUtils.toString(response.getEntity(), "UTF-8");
        } else {
            result = EntityUtils.toString(response.getEntity(), "UTF-8") + response.getStatusLine().getStatusCode() + "ERROR";
        }
    } catch (ConnectTimeoutException e) {
        result = "TIMEOUTERROR";
    } catch (Exception e) {
        result = "OTHERERROR";
        e.printStackTrace();
    }
    return result;
}
Also used : HttpPost(org.apache.http.client.methods.HttpPost) HttpEntity(org.apache.http.HttpEntity) ArrayList(java.util.ArrayList) HttpResponse(org.apache.http.HttpResponse) UrlEncodedFormEntity(org.apache.http.client.entity.UrlEncodedFormEntity) DefaultHttpClient(org.apache.http.impl.client.DefaultHttpClient) ConnectTimeoutException(org.apache.http.conn.ConnectTimeoutException) IOException(java.io.IOException) DefaultHttpClient(org.apache.http.impl.client.DefaultHttpClient) HttpClient(org.apache.http.client.HttpClient) BasicNameValuePair(org.apache.http.message.BasicNameValuePair) HashMap(java.util.HashMap) Map(java.util.Map) ConnectTimeoutException(org.apache.http.conn.ConnectTimeoutException)

Example 7 with ConnectTimeoutException

use of org.apache.http.conn.ConnectTimeoutException in project SmartAndroidSource by jaychou2012.

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() == null ? null : request.getCacheEntry().data, responseHeaders, true);
            }
            // 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);
        } 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 {
                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.smartandroid.sa.vl.ServerError) HttpResponse(org.apache.http.HttpResponse) AuthFailureError(com.smartandroid.sa.vl.AuthFailureError) NetworkError(com.smartandroid.sa.vl.NetworkError) NoConnectionError(com.smartandroid.sa.vl.NoConnectionError) IOException(java.io.IOException) TimeoutError(com.smartandroid.sa.vl.TimeoutError) StatusLine(org.apache.http.StatusLine) SocketTimeoutException(java.net.SocketTimeoutException) NetworkResponse(com.smartandroid.sa.vl.NetworkResponse) ConnectTimeoutException(org.apache.http.conn.ConnectTimeoutException)

Example 8 with ConnectTimeoutException

use of org.apache.http.conn.ConnectTimeoutException in project android-volley by mcxiaoke.

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<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) {
                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);
            }
            // Handle moved resources
            if (statusCode == HttpStatus.SC_MOVED_PERMANENTLY || statusCode == HttpStatus.SC_MOVED_TEMPORARILY) {
                String newUrl = responseHeaders.get("Location");
                request.setRedirectUrl(newUrl);
            }
            // 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 (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 {
                throw new NoConnectionError(e);
            }
            if (statusCode == HttpStatus.SC_MOVED_PERMANENTLY || statusCode == HttpStatus.SC_MOVED_TEMPORARILY) {
                VolleyLog.e("Request at %s has been redirected to %s", request.getOriginUrl(), request.getUrl());
            } else {
                VolleyLog.e("Unexpected response code %d for %s", statusCode, request.getUrl());
            }
            if (responseContents != null) {
                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 if (statusCode == HttpStatus.SC_MOVED_PERMANENTLY || statusCode == HttpStatus.SC_MOVED_TEMPORARILY) {
                    attemptRetryOnException("redirect", request, new RedirectError(networkResponse));
                } else {
                    // TODO: Only throw ServerError for 5xx status codes.
                    throw new ServerError(networkResponse);
                }
            } else {
                throw new NetworkError(e);
            }
        }
    }
}
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) RedirectError(com.android.volley.RedirectError) ConnectTimeoutException(org.apache.http.conn.ConnectTimeoutException)

Example 9 with ConnectTimeoutException

use of org.apache.http.conn.ConnectTimeoutException in project custom-cert-https by nelenkov.

the class MySSLSocketFactory method connectSocket.

@Override
public Socket connectSocket(Socket sock, String host, int port, InetAddress localAddress, int localPort, HttpParams params) throws IOException, UnknownHostException, ConnectTimeoutException {
    if (host == null) {
        throw new IllegalArgumentException("Target host may not be null.");
    }
    if (params == null) {
        throw new IllegalArgumentException("Parameters may not be null.");
    }
    SSLSocket sslsock = (SSLSocket) ((sock != null) ? sock : createSocket());
    if ((localAddress != null) || (localPort > 0)) {
        if (localPort < 0)
            localPort = 0;
        InetSocketAddress isa = new InetSocketAddress(localAddress, localPort);
        sslsock.bind(isa);
    }
    int connTimeout = HttpConnectionParams.getConnectionTimeout(params);
    int soTimeout = HttpConnectionParams.getSoTimeout(params);
    InetSocketAddress remoteAddress = new InetSocketAddress(host, port);
    sslsock.connect(remoteAddress, connTimeout);
    sslsock.setSoTimeout(soTimeout);
    try {
        hostnameVerifier.verify(host, sslsock);
    } catch (IOException iox) {
        try {
            sslsock.close();
        } catch (Exception x) {
        }
        throw iox;
    }
    return sslsock;
}
Also used : InetSocketAddress(java.net.InetSocketAddress) SSLSocket(javax.net.ssl.SSLSocket) IOException(java.io.IOException) IOException(java.io.IOException) UnknownHostException(java.net.UnknownHostException) ConnectTimeoutException(org.apache.http.conn.ConnectTimeoutException)

Example 10 with ConnectTimeoutException

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

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)

Aggregations

ConnectTimeoutException (org.apache.http.conn.ConnectTimeoutException)38 IOException (java.io.IOException)17 SocketTimeoutException (java.net.SocketTimeoutException)16 HttpResponse (org.apache.http.HttpResponse)14 HashMap (java.util.HashMap)12 StatusLine (org.apache.http.StatusLine)11 MalformedURLException (java.net.MalformedURLException)10 TimeoutError (com.android.volley.TimeoutError)9 SocketException (java.net.SocketException)9 AuthFailureError (com.android.volley.AuthFailureError)8 NetworkError (com.android.volley.NetworkError)8 NetworkResponse (com.android.volley.NetworkResponse)8 NoConnectionError (com.android.volley.NoConnectionError)8 ServerError (com.android.volley.ServerError)8 DefaultHttpClient (org.apache.http.impl.client.DefaultHttpClient)8 ConnectException (java.net.ConnectException)6 HttpPost (org.apache.http.client.methods.HttpPost)6 Test (org.junit.Test)6 Entry (com.android.volley.Cache.Entry)4 InetSocketAddress (java.net.InetSocketAddress)4