Search in sources :

Example 21 with ConnectTimeoutException

use of org.apache.http.conn.ConnectTimeoutException in project ThinkAndroid by white-cat.

the class FileHttpResponseHandler method copy.

public int copy(InputStream input, RandomAccessFile out) throws IOException {
    if (input == null || out == null) {
        return -1;
    }
    byte[] buffer = new byte[BUFFER_SIZE];
    BufferedInputStream in = new BufferedInputStream(input, BUFFER_SIZE);
    TALogger.v(TAG, "length" + out.length());
    int count = 0, n = 0;
    long errorBlockTimePreviousTime = -1, expireTime = 0;
    try {
        out.seek(out.length());
        previousTime = System.currentTimeMillis();
        while (!interrupt) {
            n = in.read(buffer, 0, BUFFER_SIZE);
            if (n == -1) {
                break;
            }
            out.write(buffer, 0, n);
            count += n;
            if (networkSpeed == 0) {
                if (errorBlockTimePreviousTime > 0) {
                    expireTime = System.currentTimeMillis() - errorBlockTimePreviousTime;
                    if (expireTime > TIME_OUT) {
                        throw new ConnectTimeoutException("connection time out.");
                    }
                } else {
                    errorBlockTimePreviousTime = System.currentTimeMillis();
                }
            } else {
                expireTime = 0;
                errorBlockTimePreviousTime = -1;
            }
        }
    } finally {
        try {
            out.close();
        // 无法关闭 inputstram
        // input.close();
        // in.close();
        } catch (IOException e) {
        // TODO: handle exception
        }
    }
    return count;
}
Also used : BufferedInputStream(java.io.BufferedInputStream) IOException(java.io.IOException) ConnectTimeoutException(org.apache.http.conn.ConnectTimeoutException)

Example 22 with ConnectTimeoutException

use of org.apache.http.conn.ConnectTimeoutException in project TaEmCasa by Dionen.

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);
            }
            // 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;
            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;
            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 >= 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 23 with ConnectTimeoutException

use of org.apache.http.conn.ConnectTimeoutException in project galley by Commonjava.

the class AbstractHttpJob method executeHttp.

protected boolean executeHttp() throws TransferException {
    try {
        client = http.createClient(location);
        response = client.execute(request, http.createContext(location));
        final StatusLine line = response.getStatusLine();
        final int sc = line.getStatusCode();
        logger.debug("{} {} : {}", request.getMethod(), line, url);
        if (!successStatuses.contains(sc)) {
            logger.debug("Detected failure response: " + sc);
            success = TransferResponseUtils.handleUnsuccessfulResponse(request, response, location, url);
            logger.debug("Returning non-error failure response for code: " + sc);
            return false;
        }
    } catch (final NoHttpResponseException e) {
        throw new TransferTimeoutException(location, url, "Repository remote request failed for: {}. Reason: {}", e, url, e.getMessage());
    } catch (final ConnectTimeoutException e) {
        throw new TransferTimeoutException(location, url, "Repository remote request failed for: {}. Reason: {}", e, url, e.getMessage());
    } catch (final SocketTimeoutException e) {
        throw new TransferTimeoutException(location, url, "Repository remote request failed for: {}. Reason: {}", e, url, e.getMessage());
    } catch (final ClientProtocolException e) {
        throw new TransferLocationException(location, "Repository remote request failed for: {}. Reason: {}", e, url, e.getMessage());
    } catch (BadGatewayException e) {
        throw e;
    } catch (final GalleyException e) {
        throw new TransferException("Repository remote request failed for: {}. Reason: {}", e, url, e.getMessage());
    } catch (final IOException e) {
        throw new TransferLocationException(location, "Repository remote request failed for: {}. Reason: {}", e, url, e.getMessage());
    } finally {
        /*
            * we need to integrate the writeMetadata() method into the executeHttp() call in a finally block,
            * and with a condition that it only runs on HEAD or GET. This would allow us to capture metadata on failed requests too,
            * which is critical for responding consistently to the user after a failed request is cached in the NFC.
            */
        String method = request.getMethod();
        if ("GET".equalsIgnoreCase(method) || "HEAD".equalsIgnoreCase(method)) {
            Transfer target = getTransfer();
            ObjectMapper mapper = getMetadataObjectMapper();
            if (target != null && mapper != null) {
                writeMetadata(target, mapper);
            }
        }
    }
    return true;
}
Also used : NoHttpResponseException(org.apache.http.NoHttpResponseException) TransferTimeoutException(org.commonjava.maven.galley.TransferTimeoutException) IOException(java.io.IOException) GalleyException(org.commonjava.maven.galley.GalleyException) ClientProtocolException(org.apache.http.client.ClientProtocolException) StatusLine(org.apache.http.StatusLine) TransferException(org.commonjava.maven.galley.TransferException) SocketTimeoutException(java.net.SocketTimeoutException) Transfer(org.commonjava.maven.galley.model.Transfer) BadGatewayException(org.commonjava.maven.galley.BadGatewayException) TransferLocationException(org.commonjava.maven.galley.TransferLocationException) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) ConnectTimeoutException(org.apache.http.conn.ConnectTimeoutException)

Example 24 with ConnectTimeoutException

use of org.apache.http.conn.ConnectTimeoutException in project TaEmCasa by Dionen.

the class BasicNetworkTest method connectTimeout.

@Test
public void connectTimeout() throws Exception {
    MockHttpStack mockHttpStack = new MockHttpStack();
    mockHttpStack.setExceptionToThrow(new ConnectTimeoutException());
    BasicNetwork httpNetwork = new BasicNetwork(mockHttpStack);
    Request<String> request = buildRequest();
    request.setRetryPolicy(mMockRetryPolicy);
    doThrow(new VolleyError()).when(mMockRetryPolicy).retry(any(VolleyError.class));
    try {
        httpNetwork.performRequest(request);
    } catch (VolleyError e) {
    // expected
    }
    // should retry connection timeouts
    verify(mMockRetryPolicy).retry(any(TimeoutError.class));
}
Also used : VolleyError(com.android.volley.VolleyError) MockHttpStack(com.android.volley.mock.MockHttpStack) TimeoutError(com.android.volley.TimeoutError) ConnectTimeoutException(org.apache.http.conn.ConnectTimeoutException) Test(org.junit.Test)

Example 25 with ConnectTimeoutException

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

the class HttpUtils method uploadFiles.

public static String uploadFiles(String url, List<NameValuePair> paramsList, String fileParams, List<File> files) throws Exception {
    String result = "";
    try {
        DefaultHttpClient mHttpClient;
        HttpParams params = new BasicHttpParams();
        params.setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
        params.setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 30000);
        params.setParameter(CoreConnectionPNames.SO_TIMEOUT, 30000);
        mHttpClient = new DefaultHttpClient(params);
        HttpPost httpPost = new HttpPost(url);
        MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create();
        entityBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
        if (BasicUtils.judgeNotNull(paramsList)) {
            for (NameValuePair nameValuePair : paramsList) {
                entityBuilder.addTextBody(nameValuePair.getName(), nameValuePair.getValue());
            }
        }
        // entityBuilder.addBinaryBody(fileParams, file);
        for (File f : files) {
            if (f != null && f.exists())
                entityBuilder.addBinaryBody(fileParams, f);
        }
        HttpEntity entity = entityBuilder.build();
        httpPost.setEntity(entity);
        HttpResponse httpResp = mHttpClient.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 = "HttpPost failed";
        }
    } catch (ConnectTimeoutException e) {
        result = "ConnectTimeoutException";
        Logs.e("HttpPost overtime:  " + "");
    } catch (Exception e) {
        e.printStackTrace();
        Logs.e(e, "");
        result = "Exception";
    }
    return result;
}
Also used : HttpPost(org.apache.http.client.methods.HttpPost) MultipartEntityBuilder(org.apache.http.entity.mime.MultipartEntityBuilder) File(java.io.File) DefaultHttpClient(org.apache.http.impl.client.DefaultHttpClient) ConnectTimeoutException(org.apache.http.conn.ConnectTimeoutException) 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