Search in sources :

Example 51 with ConnectTimeoutException

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

the class ApacheHttpClientGetUnit method execute.

@Override
public UnitResponse execute(UnitRequest msg) {
    String url = msg.get("url", String.class);
    Map<String, String> headers = msg.get("headers");
    Integer readTimeoutInMillis = msg.get("readTimeoutInMillis", Integer.class);
    try (IApacheHttpClient httpClient = ApacheHttpClient.newInstance(url, headers, readTimeoutInMillis)) {
        JSONObject responseJSON = new JSONObject();
        HttpResponse httpResponse;
        try {
            httpResponse = RetryUtil.retryUntilNoException(httpClient::getHttpResponse, XianConfig.getIntValue("apache.httpclient.max.try", 3), ConnectTimeoutException.class);
        } catch (ConnectTimeoutException e) {
            return UnitResponse.error(ISocketGroup.CODE_CONNECT_TIMEOUT, e, "Connect timeout: " + url);
        } catch (SocketTimeoutException e) {
            return UnitResponse.error(ISocketGroup.CODE_SOCKET_TIMEOUT, e, "Read timeout: " + url);
        } catch (Throwable e) {
            return UnitResponse.exception(e);
        }
        responseJSON.put("statusLine", new JSONObject() {

            {
                put("statusCode", httpResponse.getStatusLine().getStatusCode());
                put("protocolVersion", httpResponse.getStatusLine().getProtocolVersion());
                put("reasonPhrase", httpResponse.getStatusLine().getReasonPhrase());
            }
        });
        responseJSON.put("allHeaders", httpResponse.getAllHeaders());
        try {
            responseJSON.put("entity", EntityUtils.toString(httpResponse.getEntity(), "UTF-8"));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return UnitResponse.success(responseJSON);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}
Also used : SocketTimeoutException(java.net.SocketTimeoutException) JSONObject(com.alibaba.fastjson.JSONObject) HttpResponse(org.apache.http.HttpResponse) IOException(java.io.IOException) IApacheHttpClient(info.xiancloud.httpclient.apache_http.IApacheHttpClient) ConnectTimeoutException(org.apache.http.conn.ConnectTimeoutException)

Example 52 with ConnectTimeoutException

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

the class ApacheHttpClientPostUnit method execute.

@Override
public UnitResponse execute(UnitRequest msg) {
    String url = msg.get("url", String.class);
    Map<String, String> headers = msg.get("headers");
    Integer readTimeoutInMillis = msg.get("readTimeoutInMillis", Integer.class);
    try (IApacheHttpClient httpClient = ApacheHttpClient.newInstance(url, headers, readTimeoutInMillis)) {
        JSONObject responseJSON = new JSONObject();
        String responsePayload;
        try {
            responsePayload = RetryUtil.retryUntilNoException(() -> httpClient.post(msg.get("body", String.class)), XianConfig.getIntValue("apache.httpclient.max.try", 3), // 这里对连接超时做重试,总共只尝试三次
            ConnectTimeoutException.class);
        } catch (ConnectTimeoutException e) {
            return UnitResponse.error(ISocketGroup.CODE_CONNECT_TIMEOUT, e, "Connect timeout: " + url);
        } catch (SocketTimeoutException e) {
            return UnitResponse.error(ISocketGroup.CODE_SOCKET_TIMEOUT, e, "Read timeout: " + url);
        } catch (Throwable e) {
            return UnitResponse.exception(e);
        }
        responseJSON.put("statusLine", new JSONObject() {

            {
                put("statusCode", "todo");
                put("protocolVersion", "todo");
                put("reasonPhrase", "todo");
            }
        });
        responseJSON.put("allHeaders", "todo");
        responseJSON.put("entity", responsePayload);
        return UnitResponse.success(responseJSON);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}
Also used : SocketTimeoutException(java.net.SocketTimeoutException) JSONObject(com.alibaba.fastjson.JSONObject) IOException(java.io.IOException) IApacheHttpClient(info.xiancloud.httpclient.apache_http.IApacheHttpClient) ConnectTimeoutException(org.apache.http.conn.ConnectTimeoutException)

Example 53 with ConnectTimeoutException

use of org.apache.http.conn.ConnectTimeoutException in project docker-client by spotify.

the class DefaultDockerClient method propagate.

private RuntimeException propagate(final String method, final WebTarget resource, final Exception ex) throws DockerException, InterruptedException {
    Throwable cause = ex.getCause();
    // So we unpack it here.
    if (ex instanceof MultiException) {
        cause = cause.getCause();
    }
    Response response = null;
    if (cause instanceof ResponseProcessingException) {
        response = ((ResponseProcessingException) cause).getResponse();
    } else if (cause instanceof WebApplicationException) {
        response = ((WebApplicationException) cause).getResponse();
    } else if ((cause instanceof ProcessingException) && (cause.getCause() != null)) {
        // For a ProcessingException, The exception message or nested Throwable cause SHOULD contain
        // additional information about the reason of the processing failure.
        cause = cause.getCause();
    }
    if (response != null) {
        throw new DockerRequestException(method, resource.getUri(), response.getStatus(), message(response), cause);
    } else if ((cause instanceof SocketTimeoutException) || (cause instanceof ConnectTimeoutException)) {
        throw new DockerTimeoutException(method, resource.getUri(), ex);
    } else if ((cause instanceof InterruptedIOException) || (cause instanceof InterruptedException)) {
        throw new InterruptedException("Interrupted: " + method + " " + resource);
    } else {
        throw new DockerException(ex);
    }
}
Also used : DockerException(com.spotify.docker.client.exceptions.DockerException) InterruptedIOException(java.io.InterruptedIOException) WebApplicationException(javax.ws.rs.WebApplicationException) DockerRequestException(com.spotify.docker.client.exceptions.DockerRequestException) DockerTimeoutException(com.spotify.docker.client.exceptions.DockerTimeoutException) ConfigCreateResponse(com.spotify.docker.client.messages.swarm.ConfigCreateResponse) Response(javax.ws.rs.core.Response) CloseableHttpResponse(org.apache.http.client.methods.CloseableHttpResponse) SecretCreateResponse(com.spotify.docker.client.messages.swarm.SecretCreateResponse) ServiceCreateResponse(com.spotify.docker.client.messages.ServiceCreateResponse) SocketTimeoutException(java.net.SocketTimeoutException) ResponseProcessingException(javax.ws.rs.client.ResponseProcessingException) MultiException(org.glassfish.hk2.api.MultiException) ProcessingException(javax.ws.rs.ProcessingException) ResponseProcessingException(javax.ws.rs.client.ResponseProcessingException) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) ConnectTimeoutException(org.apache.http.conn.ConnectTimeoutException)

Example 54 with ConnectTimeoutException

use of org.apache.http.conn.ConnectTimeoutException in project vespa by vespa-engine.

the class HTTPSearcher method getResponse.

/**
 * Executes an HTTP request and gets the response.
 * @param uri the request URI.
 * @param requestMeta a meta hit that holds logging information about this request (may be {@code null}).
 * @param connectionTimeout how long to wait for getting a connection
 * @param readTimeout timeout for reading HTTP data
 */
protected HttpResponse getResponse(URI uri, HttpEntity reqEntity, Map<String, String> reqHeaders, Hit requestMeta, int connectionTimeout, int readTimeout) throws IOException {
    HttpParams httpParams = httpParameters.toHttpParams(connectionTimeout, readTimeout);
    HttpClient httpClient = createClient(httpParams);
    long start = 0L;
    HttpUriRequest request;
    if (httpParameters.getEnableProxy() && "http".equals(httpParameters.getProxyType())) {
        HttpHost proxy = new HttpHost(httpParameters.getProxyHost(), httpParameters.getProxyPort(), httpParameters.getProxyType());
        httpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
        // Logging
        if (requestMeta != null) {
            requestMeta.setField(LOG_PROXY_TYPE, httpParameters.getProxyType());
            requestMeta.setField(LOG_PROXY_HOST, httpParameters.getProxyHost());
            requestMeta.setField(LOG_PROXY_PORT, httpParameters.getProxyPort());
        }
    }
    if (reqEntity == null) {
        request = createRequest(httpParameters.getMethod(), uri);
    } else {
        request = createRequest(httpParameters.getMethod(), uri, reqEntity);
    }
    if (reqHeaders != null) {
        for (Entry<String, String> entry : reqHeaders.entrySet()) {
            if (entry.getValue() == null || isAscii(entry.getValue())) {
                request.addHeader(entry.getKey(), entry.getValue());
            } else {
                byte[] asBytes = Utf8.toBytes(entry.getValue());
                String asLyingString = new String(asBytes, 0, asBytes.length, iso8859Charset);
                request.addHeader(entry.getKey(), asLyingString);
            }
        }
    }
    // Logging
    if (requestMeta != null) {
        for (HeaderIterator headers = request.headerIterator(); headers.hasNext(); ) {
            Header h = headers.nextHeader();
            requestMeta.setField(LOG_HEADER_PREFIX + h.getName(), h.getValue());
        }
        start = System.currentTimeMillis();
    }
    HttpResponse response;
    try {
        HttpContext context = new BasicHttpContext();
        response = httpClient.execute(request, context);
        if (requestMeta != null) {
            requestMeta.setField(LOG_IP_ADDRESS, getIpAddress(context));
        }
    } catch (ConnectTimeoutException e) {
        connectTimeouts.increment();
        throw e;
    }
    // Logging
    long latencyStart = System.currentTimeMillis() - start;
    if (requestMeta != null) {
        requestMeta.setField(LOG_LATENCY_START, latencyStart);
    }
    logResponseLatency(latencyStart);
    return response;
}
Also used : HttpUriRequest(org.apache.http.client.methods.HttpUriRequest) BasicHttpContext(org.apache.http.protocol.BasicHttpContext) BasicHttpContext(org.apache.http.protocol.BasicHttpContext) HttpContext(org.apache.http.protocol.HttpContext) HttpParams(org.apache.http.params.HttpParams) DefaultHttpClient(org.apache.http.impl.client.DefaultHttpClient) HttpClient(org.apache.http.client.HttpClient) ConnectTimeoutException(org.apache.http.conn.ConnectTimeoutException)

Example 55 with ConnectTimeoutException

use of org.apache.http.conn.ConnectTimeoutException in project aliyun-oss-java-sdk by aliyun.

the class ExceptionFactoryTest method testCreateNetworkException.

@Test
public void testCreateNetworkException() {
    SocketTimeoutException ste = new SocketTimeoutException();
    ClientException ex = ExceptionFactory.createNetworkException(ste);
    assertEquals(ex.getErrorCode(), ClientErrorCode.SOCKET_TIMEOUT);
    ConnectTimeoutException cte = new ConnectTimeoutException();
    ex = ExceptionFactory.createNetworkException(cte);
    assertEquals(ex.getErrorCode(), ClientErrorCode.CONNECTION_TIMEOUT);
    IOException ioe = new IOException();
    ex = ExceptionFactory.createNetworkException(ioe);
    assertEquals(ex.getErrorCode(), ClientErrorCode.UNKNOWN);
}
Also used : SocketTimeoutException(java.net.SocketTimeoutException) ClientException(com.aliyun.oss.ClientException) IOException(java.io.IOException) ConnectTimeoutException(org.apache.http.conn.ConnectTimeoutException) Test(org.junit.Test)

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