Search in sources :

Example 31 with HttpHostConnectException

use of org.apache.http.conn.HttpHostConnectException in project jenkin-qtest-plugin by QASymphony.

the class HttpClientUtils method getHttpClient.

public static HttpClient getHttpClient(String hostUrl) throws Exception {
    int timeout;
    try {
        timeout = Integer.parseInt(System.getenv("SOCKET_TIMEOUT"));
    } catch (Exception e) {
        timeout = DEFAULT_SOCKET_TIMEOUT;
    }
    HttpClientBuilder httpClientBuilder = HttpClientBuilder.create().useSystemProperties();
    setHttpProxy(httpClientBuilder, hostUrl);
    SSLConnectionSocketFactory sslSocketFactory = getSslSocketFactory();
    httpClientBuilder.setSSLSocketFactory(sslSocketFactory).setConnectionReuseStrategy(new NoConnectionReuseStrategy());
    timeout = timeout * 1000;
    httpClientBuilder.setDefaultRequestConfig(RequestConfig.custom().setSocketTimeout(timeout).setConnectTimeout(timeout).setConnectionRequestTimeout(timeout).build());
    httpClientBuilder.setRetryHandler(new DefaultHttpRequestRetryHandler(RETRY_MAX_COUNT, RETRY_REQUEST_SEND_RETRY_ENABLED) {

        @Override
        public boolean retryRequest(IOException exception, int executionCount, HttpContext context) {
            if (executionCount > this.getRetryCount())
                return false;
            if (exception instanceof HttpHostConnectException)
                return true;
            return super.retryRequest(exception, executionCount, context);
        }
    });
    return httpClientBuilder.build();
}
Also used : NoConnectionReuseStrategy(org.apache.http.impl.NoConnectionReuseStrategy) DefaultHttpRequestRetryHandler(org.apache.http.impl.client.DefaultHttpRequestRetryHandler) HttpContext(org.apache.http.protocol.HttpContext) HttpHostConnectException(org.apache.http.conn.HttpHostConnectException) HttpClientBuilder(org.apache.http.impl.client.HttpClientBuilder) IOException(java.io.IOException) SSLConnectionSocketFactory(org.apache.http.conn.ssl.SSLConnectionSocketFactory) KeyStoreException(java.security.KeyStoreException) HttpHostConnectException(org.apache.http.conn.HttpHostConnectException) IOException(java.io.IOException) KeyManagementException(java.security.KeyManagementException) CertificateException(java.security.cert.CertificateException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException)

Example 32 with HttpHostConnectException

use of org.apache.http.conn.HttpHostConnectException in project dropwizard by dropwizard.

the class DropwizardApacheConnectorTest method connect_timeout_override_changes_how_long_it_takes_for_a_connection_to_timeout.

/**
 * <p>In first assertion we prove, that a request takes no longer than:
 * <em>request_time < connect_timeout + error_margin</em> (1)</p>
 * <p/>
 * </p>In the second we show that if we set <b>connect_timeout</b> to
 * <b>set_connect_timeout + increase + error_margin</b> then
 * <em>request_time > connect_timeout + increase + error_margin</em> (2)</p>
 * <p/>
 * <p>Now, (1) and (2) can hold at the same time if then connect_timeout update was successful.</p>
 */
@Test
@Disabled("Flaky, timeout jumps over the threshold")
void connect_timeout_override_changes_how_long_it_takes_for_a_connection_to_timeout() {
    // setUp override
    WebTarget target = client.target(NON_ROUTABLE_ADDRESS);
    // This can't be tested without a real connection
    try {
        target.request().get(Response.class);
    } catch (ProcessingException e) {
        if (e.getCause() instanceof HttpHostConnectException) {
            return;
        }
    }
    assertThatConnectionTimeoutFor(target).isLessThan(DEFAULT_CONNECT_TIMEOUT_IN_MILLIS + ERROR_MARGIN_IN_MILLIS);
    // tearDown override
    final int newTimeout = DEFAULT_CONNECT_TIMEOUT_IN_MILLIS + INCREASE_IN_MILLIS + ERROR_MARGIN_IN_MILLIS;
    final WebTarget newTarget = target.property(ClientProperties.CONNECT_TIMEOUT, newTimeout);
    assertThatConnectionTimeoutFor(newTarget).isGreaterThan(newTimeout);
}
Also used : HttpHostConnectException(org.apache.http.conn.HttpHostConnectException) WebTarget(javax.ws.rs.client.WebTarget) ProcessingException(javax.ws.rs.ProcessingException) Test(org.junit.jupiter.api.Test) Disabled(org.junit.jupiter.api.Disabled)

Example 33 with HttpHostConnectException

use of org.apache.http.conn.HttpHostConnectException in project new-cloud by xie-summer.

the class HttpUtils method uploadFile.

/**
 * @param url
 * @param params
 * @param uploadMap
 * @param fileNameMap
 * @param encode
 * @return
 */
public static HttpResult uploadFile(String url, Map<String, String> params, Map<String, byte[]> uploadMap, Map<String, String> fileNameMap, String encode, int timeout) {
    /**
     * DefaultHttpClient client = new DefaultHttpClient();
     * client.getParams().setIntParameter("http.socket.timeout",
     * LONG_TIMEOUT); client.getParams().setBooleanParameter(
     * "http.protocol.expect-continue", false);
     * client.getParams().setIntParameter("http.connection.timeout",
     * CONNECTION_TIMEOUT);
     */
    CookieStore cookieStore = getCookieStore(null);
    CloseableHttpClient client = getHttpClient(CONNECTION_TIMEOUT, timeout, cookieStore);
    MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create().setCharset(Charset.forName(encode));
    HttpPost request = new HttpPost(url);
    // MultipartEntity reqEntity = new MultipartEntity();
    for (String input : uploadMap.keySet()) {
        ByteArrayBody isb = new ByteArrayBody(uploadMap.get(input), fileNameMap.get(input));
        multipartEntityBuilder.addPart(input, isb);
    }
    try {
        if (params != null && !params.isEmpty()) {
            for (String key : params.keySet()) {
                multipartEntityBuilder.addTextBody(key, params.get(key), ContentType.create("text/plain", Charset.forName(encode)));
            }
        }
        request.setEntity(multipartEntityBuilder.build());
        List<Cookie> reqcookie = cookieStore.getCookies();
        CloseableHttpResponse response = client.execute(request);
        try {
            String result = "";
            HttpEntity entity = getEntity(response);
            if (entity != null) {
                result = EntityUtils.toString(entity, encode);
            }
            if (isSuccess(response)) {
                HttpResult ret = HttpResult.getSuccessReturn(result);
                addHeader(ret, response);
                List<Cookie> cookies = cookieStore.getCookies();
                addCookie(ret, cookies, reqcookie);
                return ret;
            } else {
                int statusCode = response.getStatusLine().getStatusCode();
                String msg = "httpStatus:" + statusCode + response.getStatusLine().getReasonPhrase() + ", Header: ";
                Header[] headers = response.getAllHeaders();
                for (Header header : headers) {
                    msg += header.getName() + ":" + header.getValue();
                }
                request.abort();
                DB_LOGGER.error("ERROR HttpUtils:" + msg + request.getURI());
                return HttpResult.getFailure("httpStatus:" + response.getStatusLine().getStatusCode(), statusCode, result);
            }
        } finally {
            response.close();
        }
    } catch (HttpHostConnectException e) {
        request.abort();
        DB_LOGGER.error(request.getURI() + ":" + LoggerUtils.getExceptionTrace(e, 30));
        return HttpResult.getFailure(request.getURI() + " exception:" + e.getClass().getCanonicalName(), HTTP_STATUSCODE_HTTP_HOST_CONNECT_EXCEPTION);
    } catch (ConnectTimeoutException e) {
        request.abort();
        DB_LOGGER.error(request.getURI() + ":" + LoggerUtils.getExceptionTrace(e, 30));
        return HttpResult.getFailure(request.getURI() + " exception:" + e.getClass().getCanonicalName(), HTTP_STATUSCODE_CONNECT_TIMEOUT_EXCEPTION);
    } catch (SocketTimeoutException e) {
        request.abort();
        DB_LOGGER.error(request.getURI() + ":" + LoggerUtils.getExceptionTrace(e, 30));
        return HttpResult.getFailure(request.getURI() + " exception:" + e.getClass().getCanonicalName(), HTTP_STATUSCODE_SOCKET_TIMEOUT_EXCEPTION);
    } catch (Exception e) {
        request.abort();
        DB_LOGGER.error(request.getURI() + ":" + LoggerUtils.getExceptionTrace(e, 100));
        return HttpResult.getFailure(request.getURI() + " exception:" + e.getClass().getCanonicalName(), EXCEPTION_HTTP_STATUSCODE);
    }
}
Also used : Cookie(org.apache.http.cookie.Cookie) BasicClientCookie(org.apache.http.impl.cookie.BasicClientCookie) CloseableHttpClient(org.apache.http.impl.client.CloseableHttpClient) HttpPost(org.apache.http.client.methods.HttpPost) MultipartEntityBuilder(org.apache.http.entity.mime.MultipartEntityBuilder) ByteArrayBody(org.apache.http.entity.mime.content.ByteArrayBody) HttpHostConnectException(org.apache.http.conn.HttpHostConnectException) KeyManagementException(java.security.KeyManagementException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) ConnectTimeoutException(org.apache.http.conn.ConnectTimeoutException) SocketTimeoutException(java.net.SocketTimeoutException) CookieStore(org.apache.http.client.CookieStore) BasicCookieStore(org.apache.http.impl.client.BasicCookieStore) SocketTimeoutException(java.net.SocketTimeoutException) CloseableHttpResponse(org.apache.http.client.methods.CloseableHttpResponse) HttpHostConnectException(org.apache.http.conn.HttpHostConnectException) ConnectTimeoutException(org.apache.http.conn.ConnectTimeoutException)

Example 34 with HttpHostConnectException

use of org.apache.http.conn.HttpHostConnectException in project LogHub by fbacchella.

the class AbstractHttpSender method doRequest.

protected HttpResponse doRequest(HttpRequest therequest) {
    CloseableHttpResponse response = null;
    HttpClientContext context = HttpClientContext.create();
    if (credsProvider != null) {
        context.setCredentialsProvider(credsProvider);
    }
    HttpHost host;
    RequestLine requestLine = new BasicRequestLine(therequest.verb, therequest.url.getPath(), therequest.httpVersion);
    BasicHttpEntityEnclosingRequest request = new BasicHttpEntityEnclosingRequest(requestLine);
    if (therequest.content != null) {
        request.setEntity(therequest.content);
    }
    therequest.headers.forEach((i, j) -> request.addHeader(i, j));
    host = new HttpHost(therequest.url.getHost(), therequest.url.getPort(), therequest.url.getProtocol());
    try {
        response = client.execute(host, request, context);
    } catch (ConnectionPoolTimeoutException e) {
        logger.error("Connection to {} timed out", host);
        return new HttpResponse(host, null, e, null);
    } catch (HttpHostConnectException e) {
        String message = "";
        try {
            throw e.getCause();
        } catch (ConnectException e1) {
            message = String.format("Connection to %s refused", host);
        } catch (SocketTimeoutException e1) {
            message = String.format("Slow response from %s", host);
        } catch (Throwable e1) {
            message = String.format("Connection to %s failed: %s", host, e1.getMessage());
            logger.catching(Level.DEBUG, e1);
        }
        logger.error(message);
        logger.catching(Level.DEBUG, e.getCause());
        return new HttpResponse(host, null, e, null);
    } catch (IOException e) {
        Throwable rootCause = e;
        while (rootCause.getCause() != null) {
            rootCause = rootCause.getCause();
        }
        ;
        // A TLS exception, will not help to retry
        if (rootCause instanceof GeneralSecurityException) {
            logger.error("Secure comunication with {} failed: {}", host, rootCause.getMessage());
            logger.catching(Level.DEBUG, rootCause);
            return new HttpResponse(host, null, null, (GeneralSecurityException) rootCause);
        } else {
            logger.error("Comunication with {} failed: {}", host, e.getMessage());
            logger.catching(Level.DEBUG, e);
            return new HttpResponse(host, null, e, null);
        }
    }
    if (response == null) {
        logger.error("give up trying to connect to " + getPublishName());
        return null;
    }
    ;
    return new HttpResponse(host, response, null, null);
}
Also used : GeneralSecurityException(java.security.GeneralSecurityException) CloseableHttpResponse(org.apache.http.client.methods.CloseableHttpResponse) HttpClientContext(org.apache.http.client.protocol.HttpClientContext) UncheckedIOException(java.io.UncheckedIOException) IOException(java.io.IOException) ConnectionPoolTimeoutException(org.apache.http.conn.ConnectionPoolTimeoutException) RequestLine(org.apache.http.RequestLine) BasicRequestLine(org.apache.http.message.BasicRequestLine) SocketTimeoutException(java.net.SocketTimeoutException) HttpHost(org.apache.http.HttpHost) BasicRequestLine(org.apache.http.message.BasicRequestLine) CloseableHttpResponse(org.apache.http.client.methods.CloseableHttpResponse) HttpHostConnectException(org.apache.http.conn.HttpHostConnectException) BasicHttpEntityEnclosingRequest(org.apache.http.message.BasicHttpEntityEnclosingRequest) HttpHostConnectException(org.apache.http.conn.HttpHostConnectException) ConnectException(java.net.ConnectException)

Example 35 with HttpHostConnectException

use of org.apache.http.conn.HttpHostConnectException in project providence by morimekta.

the class HttpClientHandlerNetworkTest method testSimpleRequest_connectionRefused_apacheHttpTransport.

@Test
public void testSimpleRequest_connectionRefused_apacheHttpTransport() throws IOException, Failure {
    HttpRequestFactory factory = new ApacheHttpTransport().createRequestFactory();
    GenericUrl url = new GenericUrl("http://localhost:" + (port - 10) + "/" + ENDPOINT);
    TestService.Iface client = new TestService.Client(new HttpClientHandler(() -> url, factory, provider));
    try {
        client.test(new Request("request"));
        fail("No exception");
    } catch (HttpHostConnectException ex) {
        assertThat(ex.getMessage(), allOf(startsWith("Connect to localhost:" + (port - 10) + " failed: "), containsString("Connection refused")));
    }
}
Also used : HttpRequestFactory(com.google.api.client.http.HttpRequestFactory) TestService(net.morimekta.test.providence.client.TestService) Request(net.morimekta.test.providence.client.Request) HttpHostConnectException(org.apache.http.conn.HttpHostConnectException) GenericUrl(com.google.api.client.http.GenericUrl) ApacheHttpTransport(com.google.api.client.http.apache.ApacheHttpTransport) Test(org.junit.Test)

Aggregations

HttpHostConnectException (org.apache.http.conn.HttpHostConnectException)37 ConnectTimeoutException (org.apache.http.conn.ConnectTimeoutException)11 IOException (java.io.IOException)10 ConnectException (java.net.ConnectException)10 SocketTimeoutException (java.net.SocketTimeoutException)10 Socket (java.net.Socket)7 HttpResponse (org.apache.http.HttpResponse)6 CloseableHttpResponse (org.apache.http.client.methods.CloseableHttpResponse)6 LayeredSocketFactory (org.apache.http.conn.scheme.LayeredSocketFactory)6 Scheme (org.apache.http.conn.scheme.Scheme)6 Test (org.junit.Test)5 InputStream (java.io.InputStream)4 GenericUrl (com.google.api.client.http.GenericUrl)3 InetAddress (java.net.InetAddress)3 NoRouteToHostException (java.net.NoRouteToHostException)3 SocketException (java.net.SocketException)3 UnknownHostException (java.net.UnknownHostException)3 HttpEntity (org.apache.http.HttpEntity)3 HttpHost (org.apache.http.HttpHost)3 ClientProtocolException (org.apache.http.client.ClientProtocolException)3