org.apache.http.conn.ConnectTimeoutException Java Examples

The following examples show how to use org.apache.http.conn.ConnectTimeoutException. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: BasePresenter.java    From OpenHub with GNU General Public License v3.0 6 votes vote down vote up
@NonNull
protected String getErrorTip(@NonNull Throwable error) {
    String errorTip = null;
    if(error == null){
        return errorTip;
    }
    if(error instanceof UnknownHostException){
        errorTip = getString(R.string.no_network_tip);
    } else if (error instanceof SocketTimeoutException || error instanceof ConnectTimeoutException) {
        errorTip = getString(R.string.load_timeout_tip);
    } else if (error instanceof HttpError) {
        errorTip = error.getMessage();
    } else {
        errorTip = StringUtils.isBlank(error.getMessage()) ? error.toString() : error.getMessage();
    }
    return errorTip;
}
 
Example #2
Source File: EasySSLSocketFactory.java    From PanoramaGL with Apache License 2.0 6 votes vote down vote up
/**
 * @see org.apache.http.conn.scheme.SocketFactory#connectSocket(java.net.Socket,
 *      java.lang.String, int, java.net.InetAddress, int,
 *      org.apache.http.params.HttpParams)
 */
public Socket connectSocket(Socket sock, String host, int port,
                InetAddress localAddress, int localPort, HttpParams params)
                throws IOException, UnknownHostException, ConnectTimeoutException {
        int connTimeout = HttpConnectionParams.getConnectionTimeout(params);
        int soTimeout = HttpConnectionParams.getSoTimeout(params);

        InetSocketAddress remoteAddress = new InetSocketAddress(host, port);
        SSLSocket sslsock = (SSLSocket) ((sock != null) ? sock : createSocket());

        if ((localAddress != null) || (localPort > 0)) {
                // we need to bind explicitly
                if (localPort < 0) {
                        localPort = 0; // indicates "any"
                }
                InetSocketAddress isa = new InetSocketAddress(localAddress,
                                localPort);
                sslsock.bind(isa);
        }

        sslsock.connect(remoteAddress, connTimeout);
        sslsock.setSoTimeout(soTimeout);
        return sslsock;

}
 
Example #3
Source File: ApacheHttpClient.java    From xian with Apache License 2.0 6 votes vote down vote up
@Override
public HttpResponse getHttpResponse() throws ConnectTimeoutException, SocketTimeoutException {
    if (client == null) {
        throw new RuntimeException("http客户端未初始化!");
    }
    HttpGet httpGet = new HttpGet(url);
    httpGet.setProtocolVersion(HttpVersion.HTTP_1_1);
    if (headers != null) {
        for (Map.Entry<String, String> entry : headers.entrySet()) {
            httpGet.setHeader(entry.getKey(), entry.getValue());
        }
    }
    try {
        httpGet.setConfig(requestConfig);
        return client.execute(httpGet);
    } catch (ConnectTimeoutException | SocketTimeoutException connectOrReadTimeout) {
        throw connectOrReadTimeout;
    } catch (Throwable e) {
        throw new RuntimeException(e);
    }
}
 
Example #4
Source File: ApacheHttpClient.java    From xian with Apache License 2.0 6 votes vote down vote up
@Override
public String get() throws ConnectTimeoutException, SocketTimeoutException {
    if (client == null) {
        return INIT_FAIL;
    }
    HttpGet httpGet = new HttpGet(url);
    httpGet.setProtocolVersion(HttpVersion.HTTP_1_1);
    if (headers != null) {
        for (Map.Entry<String, String> entry : headers.entrySet()) {
            httpGet.setHeader(entry.getKey(), entry.getValue());
        }
    }
    String responseContent;
    try {
        httpGet.setConfig(requestConfig);
        HttpResponse httpResponse = client.execute(httpGet);
        responseContent = EntityUtils.toString(httpResponse.getEntity(), "UTF-8");
    } catch (ConnectTimeoutException | SocketTimeoutException connectOrReadTimeout) {
        throw connectOrReadTimeout;
    } catch (Exception e) {
        throw new RuntimeException(e);
    } finally {
        httpGet.releaseConnection();
    }
    return responseContent;
}
 
Example #5
Source File: AmazonHttpClientSslHandshakeTimeoutIntegrationTest.java    From ibm-cos-sdk-java with Apache License 2.0 6 votes vote down vote up
@Test(timeout = 60 * 1000)
public void testSslHandshakeTimeout() {
    AmazonHttpClient httpClient = new AmazonHttpClient(new ClientConfiguration()
            .withSocketTimeout(CLIENT_SOCKET_TO).withMaxErrorRetry(0));

    System.out.println("Sending request to localhost...");

    try {
        httpClient.requestExecutionBuilder()
                .request(new EmptyHttpRequest(server.getHttpsEndpoint(), HttpMethodName.GET))
                .execute();
        fail("Client-side socket read timeout is expected!");

    } catch (AmazonClientException e) {
        /**
         * Http client catches the SocketTimeoutException and throws a
         * ConnectTimeoutException.
         * {@link org.apache.http.impl.conn.DefaultHttpClientConnectionOperator#connect(ManagedHttpClientConnection, HttpHost, InetSocketAddress, int, SocketConfig, HttpContext)}
         */
        Assert.assertTrue(e.getCause() instanceof ConnectTimeoutException);

        ConnectTimeoutException cte = (ConnectTimeoutException) e.getCause();
        Assert.assertThat(cte.getMessage(), org.hamcrest.Matchers
                .containsString("Read timed out"));
    }
}
 
Example #6
Source File: ApacheHttpRequester.java    From algoliasearch-client-java-2 with MIT License 6 votes vote down vote up
/**
 * Sends the http request asynchronously to the API If the request is time out it creates a new
 * response object with timeout set to true Otherwise it throws a run time exception
 *
 * @param request the request to send
 * @throws AlgoliaRuntimeException When an error occurred while sending the request
 */
public CompletableFuture<HttpResponse> performRequestAsync(HttpRequest request) {
  HttpRequestBase requestToSend = buildRequest(request);
  return toCompletableFuture(fc -> asyncHttpClient.execute(requestToSend, fc))
      .thenApplyAsync(this::buildResponse, config.getExecutor())
      .exceptionally(
          t -> {
            if (t.getCause() instanceof ConnectTimeoutException
                || t.getCause() instanceof SocketTimeoutException
                || t.getCause() instanceof ConnectException
                || t.getCause() instanceof TimeoutException
                || t.getCause() instanceof ConnectionPoolTimeoutException
                || t.getCause() instanceof NoHttpResponseException) {
              return new HttpResponse(true);
            } else if (t.getCause() instanceof HttpException) {
              return new HttpResponse().setNetworkError(true);
            }
            throw new AlgoliaRuntimeException(t);
          });
}
 
Example #7
Source File: PartitionAwareServiceFactoryTest.java    From emodb with Apache License 2.0 6 votes vote down vote up
@Test
public void testDelegateConnectionTimeoutException() throws Exception {
    doThrow(new ClientHandlerException(new ConnectTimeoutException())).when(_delegate).doIt();
    TestInterface service = _serviceFactory.create(_remoteEndPoint);

    try {
        service.doIt();
    } catch (PartitionForwardingException e) {
        assertTrue(e.getCause() instanceof ConnectTimeoutException);
    }

    assertEquals(_metricRegistry.getMeters().get("bv.emodb.web.partition-forwarding.TestInterface.errors").getCount(), 1);

    verify(_delegateServiceFactory).create(_remoteEndPoint);
    verify(_delegate).doIt();

}
 
Example #8
Source File: DefaultBulkRetryHandler.java    From bboss-elasticsearch with Apache License 2.0 6 votes vote down vote up
@Override
	public boolean neadRetry(Exception exception, BulkCommand bulkCommand) {
		if (exception instanceof HttpHostConnectException     //NoHttpResponseException 重试
				|| exception instanceof ConnectTimeoutException //连接超时重试
				|| exception instanceof UnknownHostException
				|| exception instanceof NoHttpResponseException
				|| exception instanceof NoServerElasticSearchException
//              || exception instanceof SocketTimeoutException    //响应超时不重试,避免造成业务数据不一致
		) {

			return true;
		}

		if(exception instanceof SocketException){
			String message = exception.getMessage();
			if(message != null && message.trim().equals("Connection reset")) {
				return true;
			}
		}

		return false;
	}
 
Example #9
Source File: InternalHttpCaller.java    From AndroidWear-OpenWear with MIT License 5 votes vote down vote up
private void handleError(int statusCode, Header[] headers, byte[] responseBody, Throwable error, HttpCallback callback) {
    if (callback != null) {
        if (error != null) {
            LogUtils.d(this, "error className " + error.toString());
            if (error instanceof ConnectTimeoutException ||
                    error instanceof SocketTimeoutException) {
                LogUtils.d(this, "error isTimeout");
                statusCode = TIME_OUT_CODE;
            }
        }
        callback.onError(responseBody,
                statusCode,
                makeResponseHeaders(headers));
    }
}
 
Example #10
Source File: ClickHouseExceptionSpecifier.java    From clickhouse-jdbc with Apache License 2.0 5 votes vote down vote up
private static ClickHouseException getException(Throwable cause, String host, int port) {
    if (cause instanceof SocketTimeoutException)
    // if we've got SocketTimeoutException, we'll say that the query is not good. This is not the same as SOCKET_TIMEOUT of clickhouse
    // but it actually could be a failing ClickHouse
    {
        return new ClickHouseException(ClickHouseErrorCode.TIMEOUT_EXCEEDED.code, cause, host, port);
    } else if (cause instanceof ConnectTimeoutException || cause instanceof ConnectException)
    // couldn't connect to ClickHouse during connectTimeout
    {
        return new ClickHouseException(ClickHouseErrorCode.NETWORK_ERROR.code, cause, host, port);
    } else {
        return new ClickHouseUnknownException(cause, host, port);
    }
}
 
Example #11
Source File: EasySSLSocketFactory.java    From PanoramaGL with Apache License 2.0 5 votes vote down vote up
@Override
public Socket createSocket(String arg0, int arg1, InetAddress arg2,
		int arg3,
		org.apache.commons.httpclient.params.HttpConnectionParams arg4)
		throws IOException, UnknownHostException,
		org.apache.commons.httpclient.ConnectTimeoutException {
	return getSSLContext().getSocketFactory().createSocket(arg0, arg1, arg2, arg3);
}
 
Example #12
Source File: PeerSync.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
private boolean connectTimeoutExceptionInChain(Throwable exception) {
  Throwable t = exception;
  while (true) {
    if (t instanceof ConnectTimeoutException) {
      return true;
    }
    Throwable cause = t.getCause();
    if (cause != null) {
      t = cause;
    } else {
      return false;
    }
  }
}
 
Example #13
Source File: DatabusJerseyTest.java    From emodb with Apache License 2.0 5 votes vote down vote up
@Test
public void testPollPartitionTimeout() {
    when(_client.poll(isSubject(), eq("queue-name"), eq(Duration.ofSeconds(15)), eq(123)))
            .thenThrow(new PartitionForwardingException(new ConnectTimeoutException()));

    try {
        databusClient().poll("queue-name", Duration.ofSeconds(15), 123);
    } catch (ServiceUnavailableException e) {
        // Ok
    }

    verify(_client).poll(isSubject(), eq("queue-name"), eq(Duration.ofSeconds(15)), eq(123));
    verifyNoMoreInteractions(_client);
}
 
Example #14
Source File: BasicNetworkTest.java    From SaveVolley with Apache License 2.0 5 votes vote down vote up
@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));
}
 
Example #15
Source File: AmazonHttpClientSslHandshakeTimeoutIntegrationTest.java    From aws-sdk-java-v2 with Apache License 2.0 5 votes vote down vote up
@Test(timeout = 60 * 1000)
public void testSslHandshakeTimeout() {
    AmazonSyncHttpClient httpClient = HttpTestUtils.testClientBuilder()
                                                   .retryPolicy(RetryPolicy.none())
                                                   .httpClient(ApacheHttpClient.builder()
                                                                           .socketTimeout(CLIENT_SOCKET_TO)
                                                                           .build())
                                                   .build();

    System.out.println("Sending request to localhost...");

    try {
        SdkHttpFullRequest request = server.configureHttpsEndpoint(SdkHttpFullRequest.builder())
                                           .method(SdkHttpMethod.GET)
                                           .build();
        httpClient.requestExecutionBuilder()
                  .request(request)
                  .originalRequest(NoopTestRequest.builder().build())
                  .executionContext(executionContext(request))
                  .execute(combinedSyncResponseHandler(null, new NullErrorResponseHandler()));
        fail("Client-side socket read timeout is expected!");

    } catch (SdkClientException e) {
        /**
         * Http client catches the SocketTimeoutException and throws a
         * ConnectTimeoutException.
         * {@link DefaultHttpClientConnectionOperator#connect(ManagedHttpClientConnection, HttpHost,
         * InetSocketAddress, int, SocketConfig, HttpContext)}
         */
        Assert.assertTrue(e.getCause() instanceof ConnectTimeoutException);

        ConnectTimeoutException cte = (ConnectTimeoutException) e.getCause();
        Assert.assertThat(cte.getMessage(), org.hamcrest.Matchers
                .containsString("Read timed out"));
    }
}
 
Example #16
Source File: ResponseErrorHandle.java    From DanDanPlayForAndroid with MIT License 5 votes vote down vote up
static ResponseError handleError(Throwable e) {
    ResponseError error;
    if (e instanceof HttpException) {
        HttpException exception = (HttpException) e;
        return handleHttpError(exception);
    } else if (e instanceof JsonParseException
            || e instanceof JSONException
            || e instanceof ParseException || e instanceof MalformedJsonException) {
        error = new ResponseError(e, ERROR.PARSE_ERROR);
        error.message = "解析响应数据错误";
        return error;
    } else if (e instanceof ConnectException) {
        error = new ResponseError(e, ERROR.NETWORK_ERROR);
        error.message = "连接失败,请重试";
        return error;
    } else if (e instanceof javax.net.ssl.SSLHandshakeException) {
        error = new ResponseError(e, ERROR.SSL_ERROR);
        error.message = "证书验证失败";
        return error;
    } else if (e instanceof ConnectTimeoutException) {
        error = new ResponseError(e, ERROR.TIMEOUT_ERROR);
        error.message = "连接超时,请重试";
        return error;
    } else if (e instanceof java.net.SocketTimeoutException) {
        error = new ResponseError(e, ERROR.TIMEOUT_ERROR);
        error.message = "请求超时,请重试";
        return error;
    } else {
        error = new ResponseError(e, ERROR.UNKNOWN);
        error.message = e.getMessage();
        return error;
    }
}
 
Example #17
Source File: FlowableClientService.java    From flowable-engine with Apache License 2.0 5 votes vote down vote up
public FlowableServiceException wrapException(Exception e, HttpUriRequest request) {
    if (e instanceof HttpHostConnectException) {
        return new FlowableServiceException("Unable to connect to the Flowable server.");
    } else if (e instanceof ConnectTimeoutException) {
        return new FlowableServiceException("Connection to the Flowable server timed out.");
    } else {
        // Use the raw exception message
        return new FlowableServiceException(e.getClass().getName() + ": " + e.getMessage());
    }
}
 
Example #18
Source File: ActivitiClientService.java    From activiti6-boot2 with Apache License 2.0 5 votes vote down vote up
public ActivitiServiceException wrapException(Exception e, HttpUriRequest request) {
	if (e instanceof HttpHostConnectException) {
		return new ActivitiServiceException("Unable to connect to the Activiti server.");
	} else if (e instanceof ConnectTimeoutException) {
		return new ActivitiServiceException("Connection to the Activiti server timed out.");
	} else {
		// Use the raw exception message
		return new ActivitiServiceException(e.getClass().getName() + ": " + e.getMessage());
	}
}
 
Example #19
Source File: DedupQueueJerseyTest.java    From emodb with Apache License 2.0 5 votes vote down vote up
@Test
public void testPollPartitionTimeout() {
    when(_proxy.poll(APIKEY_QUEUE, "queue-name", Duration.ofSeconds(15), 123))
            .thenThrow(new PartitionForwardingException(new ConnectTimeoutException()));

    try {
        queueClient().poll("queue-name", Duration.ofSeconds(15), 123);
    } catch (ServiceUnavailableException e) {
        // Ok
    }

    verify(_proxy).poll(APIKEY_QUEUE, "queue-name", Duration.ofSeconds(15), 123);
    verifyNoMoreInteractions(_proxy);
}
 
Example #20
Source File: HttpClientUtils.java    From paas with Apache License 2.0 5 votes vote down vote up
@Override
public boolean retryRequest(IOException exception, int executionCount, HttpContext context) {
    if (executionCount >= 3) {// 如果已经重试了3次,就放弃
        return false;
    }
    if (exception instanceof NoHttpResponseException) {// 如果服务器丢掉了连接,那么就重试
        return true;
    }
    if (exception instanceof SSLHandshakeException) {// 不要重试SSL握手异常
        return false;
    }
    if (exception instanceof InterruptedIOException) {// 超时
        return true;
    }
    if (exception instanceof UnknownHostException) {// 目标服务器不可达
        return false;
    }
    if (exception instanceof ConnectTimeoutException) {// 连接被拒绝
        return false;
    }
    if (exception instanceof SSLException) {// ssl握手异常
        return false;
    }
    HttpClientContext clientContext = HttpClientContext.adapt(context);
    HttpRequest request = clientContext.getRequest();
    // 如果请求是幂等的,就再次尝试
    if (request instanceof HttpEntityEnclosingRequest) {
        return false;
    }
    return false;
}
 
Example #21
Source File: AdaptedHttpStack.java    From volley with Apache License 2.0 5 votes vote down vote up
@Override
public HttpResponse executeRequest(Request<?> request, Map<String, String> additionalHeaders)
        throws IOException, AuthFailureError {
    org.apache.http.HttpResponse apacheResp;
    try {
        apacheResp = mHttpStack.performRequest(request, additionalHeaders);
    } catch (ConnectTimeoutException e) {
        // BasicNetwork won't know that this exception should be retried like a timeout, since
        // it's an Apache-specific error, so wrap it in a standard timeout exception.
        throw new SocketTimeoutException(e.getMessage());
    }

    int statusCode = apacheResp.getStatusLine().getStatusCode();

    org.apache.http.Header[] headers = apacheResp.getAllHeaders();
    List<Header> headerList = new ArrayList<>(headers.length);
    for (org.apache.http.Header header : headers) {
        headerList.add(new Header(header.getName(), header.getValue()));
    }

    if (apacheResp.getEntity() == null) {
        return new HttpResponse(statusCode, headerList);
    }

    long contentLength = apacheResp.getEntity().getContentLength();
    if ((int) contentLength != contentLength) {
        throw new IOException("Response too large: " + contentLength);
    }

    return new HttpResponse(
            statusCode,
            headerList,
            (int) apacheResp.getEntity().getContentLength(),
            apacheResp.getEntity().getContent());
}
 
Example #22
Source File: AdaptedHttpStackTest.java    From volley with Apache License 2.0 5 votes vote down vote up
@Test(expected = SocketTimeoutException.class)
public void requestTimeout() throws Exception {
    when(mHttpStack.performRequest(REQUEST, ADDITIONAL_HEADERS))
            .thenThrow(new ConnectTimeoutException());

    mAdaptedHttpStack.executeRequest(REQUEST, ADDITIONAL_HEADERS);
}
 
Example #23
Source File: ExceptionUtils.java    From cos-java-sdk-v5 with MIT License 5 votes vote down vote up
public static CosClientException createClientException(IOException ex) {
    String errorCode = ClientExceptionConstants.UNKNOWN;
    if (ex instanceof ConnectTimeoutException) {
        errorCode = ClientExceptionConstants.CONNECTION_TIMEOUT;
    } else if (ex instanceof UnknownHostException) {
        errorCode = ClientExceptionConstants.UNKNOWN_HOST;
    } else if (ex instanceof HttpHostConnectException) {
        errorCode = ClientExceptionConstants.HOST_CONNECT;
    } else if (ex instanceof SocketTimeoutException) {
        errorCode = ClientExceptionConstants.SOCKET_TIMEOUT;
    }

    return new CosClientException(ex.getMessage(), errorCode, ex);
}
 
Example #24
Source File: HttpProtocolParent.java    From dubbox with Apache License 2.0 5 votes vote down vote up
@Override
public boolean retryRequest(IOException exception, int executionCount, HttpContext context) {
	if (executionCount >= 5) {// 如果已经重试了5次,就放弃
		return false;
	}
	if (exception instanceof NoHttpResponseException) {// 如果服务器丢掉了连接,那么就重试
		return true;
	}
	if (exception instanceof InterruptedIOException) {// 超时
		return false;
	}
	if (exception instanceof SSLHandshakeException) {// 不要重试SSL握手异常
		return false;
	}
	if (exception instanceof UnknownHostException) {// 目标服务器不可达
		return false;
	}
	if (exception instanceof ConnectTimeoutException) {// 连接被拒绝
		return false;
	}
	if (exception instanceof SSLException) {// SSL握手异常
		return false;
	}
	HttpClientContext clientContext = HttpClientContext.adapt(context);
	HttpRequest request = clientContext.getRequest();
	// 如果请求是幂等的,就再次尝试
	if (!(request instanceof HttpEntityEnclosingRequest)) {
		return true;
	}
	return false;
}
 
Example #25
Source File: AirtableException.java    From airtable.java with MIT License 5 votes vote down vote up
/**
 * Constructs a new exception with the specified  cause.
 * @param cause the cause (which is saved for later retrieval by the
 *         {@link #getCause()} method).
 */
public AirtableException(Throwable cause) {
    super(cause);

    if(cause.getCause() instanceof ConnectTimeoutException) {
        LOG.log(Level.SEVERE, "possible forgotten to set correct apiKey or base?");
    }
}
 
Example #26
Source File: VersionService.java    From airsonic-advanced with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Resolves the latest available Airsonic version by inspecting github.
 */
private void readLatestVersion() throws IOException {

    LOG.debug("Starting to read latest version");
    RequestConfig requestConfig = RequestConfig.custom()
            .setConnectTimeout(10000)
            .setSocketTimeout(10000)
            .build();
    HttpGet method = new HttpGet(VERSION_URL);
    method.setConfig(requestConfig);
    List<Map<String, Object>> content;
    try (CloseableHttpClient client = HttpClients.createDefault()) {
        content = client.execute(method, respHandler);
    } catch (ConnectTimeoutException e) {
        LOG.warn("Got a timeout when trying to reach {}", VERSION_URL);
        return;
    }

    List<Map<String, Object>> releases = content.stream()
            .sorted(Comparator.<Map<String, Object>,Instant>comparing(r -> Instant.parse((String) r.get("published_at")), Comparator.reverseOrder()))
            .collect(Collectors.toList());


    Optional<Map<String, Object>> betaR = releases.stream().findFirst();
    Optional<Map<String, Object>> finalR = releases.stream().filter(x -> !((Boolean)x.get("draft")) && !((Boolean)x.get("prerelease"))).findFirst();
    Optional<Map<String,Object>> currentR = releases.stream().filter(x -> StringUtils.equals(build.getProperty("version") + "." + build.getProperty("timestamp"), (String) x.get("tag_name"))).findAny();

    LOG.debug("Got {} for beta version", betaR.map(x -> x.get("tag_name")).orElse(null));
    LOG.debug("Got {} for final version", finalR.map(x -> x.get("tag_name")).orElse(null));

    latestBetaVersion = betaR.map(releaseToVersionMapper).orElse(null);
    latestFinalVersion = finalR.map(releaseToVersionMapper).orElse(null);
    localVersion = currentR.map(releaseToVersionMapper).orElse(localVersion);
}
 
Example #27
Source File: HttpClientFactory.java    From springboot-security-wechat with Apache License 2.0 5 votes vote down vote up
@Override
  public boolean retryRequest(
          IOException exception,
          int executionCount,
          HttpContext context) {
if (executionCount > retryExecutionCount) {
          return false;
      }
      if (exception instanceof InterruptedIOException) {
          return false;
      }
      if (exception instanceof UnknownHostException) {
          return false;
      }
      if (exception instanceof ConnectTimeoutException) {
          return true;
      }
      if (exception instanceof SSLException) {
          return false;
      }
      HttpClientContext clientContext = HttpClientContext.adapt(context);
      HttpRequest request = clientContext.getRequest();
      boolean idempotent = !(request instanceof HttpEntityEnclosingRequest);
      if (idempotent) {
          // Retry if the request is considered idempotent
          return true;
      }
      return false;
  }
 
Example #28
Source File: RetryHandler.java    From PicCrawler with Apache License 2.0 5 votes vote down vote up
@Override
public boolean retryRequest(IOException exception, int executionCount, HttpContext context) {

    if (executionCount >= 3) {// 如果已经重试了3次,就放弃
        return false;
    }

    if (exception instanceof NoHttpResponseException) {// 如果服务器丢掉了连接,那么就重试
        return true;
    }

    if (exception instanceof SSLHandshakeException) {// 不要重试SSL握手异常
        return false;
    }

    if (exception instanceof InterruptedIOException) {// 超时
        return true;
    }

    if (exception instanceof UnknownHostException) {// 目标服务器不可达
        return false;
    }

    if (exception instanceof ConnectTimeoutException) {// 连接被拒绝
        return false;
    }

    if (exception instanceof SSLException) {// ssl握手异常
        return false;
    }

    HttpClientContext clientContext = HttpClientContext.adapt(context);
    HttpRequest request = clientContext.getRequest();

    // 如果请求是幂等的,就再次尝试
    if (!(request instanceof HttpEntityEnclosingRequest)) {
        return true;
    }
    return false;
}
 
Example #29
Source File: RetryHandler.java    From NetDiscovery with Apache License 2.0 5 votes vote down vote up
@Override
public boolean retryRequest(IOException exception, int executionCount, HttpContext context) {

    if (executionCount >= 3) {// 如果已经重试了3次,就放弃
        return false;
    }

    if (exception instanceof NoHttpResponseException) {// 如果服务器丢掉了连接,那么就重试
        return true;
    }

    if (exception instanceof SSLHandshakeException) {// 不要重试SSL握手异常
        return false;
    }

    if (exception instanceof InterruptedIOException) {// 超时
        return true;
    }

    if (exception instanceof UnknownHostException) {// 目标服务器不可达
        return false;
    }

    if (exception instanceof ConnectTimeoutException) {// 连接被拒绝
        return false;
    }

    if (exception instanceof SSLException) {// ssl握手异常
        return false;
    }

    HttpClientContext clientContext = HttpClientContext.adapt(context);
    HttpRequest request = clientContext.getRequest();

    // 如果请求是幂等的,就再次尝试
    return !(request instanceof HttpEntityEnclosingRequest);
}
 
Example #30
Source File: ElasticSearchRestClient.java    From bboss-elasticsearch with Apache License 2.0 5 votes vote down vote up
private NoServerElasticSearchException handleConnectionTimeOutException(ConnectTimeoutException ex){
	ClientConfiguration configuration = ClientConfiguration.getClientConfiguration(this.httpPool);
	if(configuration == null){
		return new NoServerElasticSearchException(ex);
	}
	else{
		StringBuilder builder = new StringBuilder();
		builder.append("Build a http connection timeout for ").append(configuration.getTimeoutConnection()).append("ms.");

		return new NoServerElasticSearchException(builder.toString(),ex);
	}
}