org.apache.http.NoHttpResponseException Java Examples

The following examples show how to use org.apache.http.NoHttpResponseException. 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: SSLTest.java    From deprecated-security-ssl with Apache License 2.0 6 votes vote down vote up
@Test
public void testHttpPlainFail() throws Exception {
    thrown.expect(NoHttpResponseException.class);

    enableHTTPClientSSL = false;
    trustHTTPServerCertificate = true;
    sendHTTPClientCertificate = false;

    final Settings settings = Settings.builder().put("opendistro_security.ssl.transport.enabled", false)
            .put(SSLConfigConstants.OPENDISTRO_SECURITY_SSL_HTTP_ENABLE_OPENSSL_IF_AVAILABLE, allowOpenSSL)
            .put(SSLConfigConstants.OPENDISTRO_SECURITY_SSL_TRANSPORT_ENABLE_OPENSSL_IF_AVAILABLE, allowOpenSSL)
            .put(SSLConfigConstants.OPENDISTRO_SECURITY_SSL_HTTP_KEYSTORE_ALIAS, "node-0").put("opendistro_security.ssl.http.enabled", true)
            .put("opendistro_security.ssl.http.clientauth_mode", "OPTIONAL")
            .put("opendistro_security.ssl.http.keystore_filepath", getAbsoluteFilePathFromClassPath("node-0-keystore.jks"))
            .put("opendistro_security.ssl.http.truststore_filepath", getAbsoluteFilePathFromClassPath("truststore.jks")).build();

    startES(settings);
    Assert.assertTrue(executeSimpleRequest("_opendistro/_security/sslinfo?pretty").length() > 0);
    Assert.assertTrue(executeSimpleRequest("_nodes/settings?pretty").contains(clustername));
    Assert.assertTrue(executeSimpleRequest("_opendistro/_security/sslinfo?pretty").contains("CN=node-0.example.com,OU=SSL,O=Test,L=Test,C=DE"));
}
 
Example #2
Source File: HttpClientUtil.java    From AndroidRobot with Apache License 2.0 6 votes vote down vote up
public boolean retryRequest(IOException exception, int executionCount,  
        HttpContext context) {  
    // 设置恢复策略,在发生异常时候将自动重试3次  
    if (executionCount >= 3) {  
        // 如果连接次数超过了最大值则停止重试  
        return false;  
    }  
    if (exception instanceof NoHttpResponseException) {  
        // 如果服务器连接失败重试  
        return true;  
    }  
    if (exception instanceof SSLHandshakeException) {  
        // 不要重试ssl连接异常  
        return false;  
    }  
    HttpRequest request = (HttpRequest) context  
            .getAttribute(ExecutionContext.HTTP_REQUEST);  
    boolean idempotent = (request instanceof HttpEntityEnclosingRequest);  
    if (!idempotent) {  
        // 重试,如果请求是考虑幂等  
        return true;  
    }  
    return false;  
}
 
Example #3
Source File: IhcHttpsClient.java    From openhab1-addons with Eclipse Public License 2.0 6 votes vote down vote up
private String sendQ(String query, int timeout)
        throws ClientProtocolException, IOException, NoHttpResponseException {
    logger.trace("Send query (timeout={}): {}", timeout, query);

    postReq.setEntity(new StringEntity(query, "UTF-8"));
    postReq.addHeader("content-type", "text/xml");

    final RequestConfig params = RequestConfig.custom().setConnectTimeout(connectTimeout).setSocketTimeout(timeout)
            .build();
    postReq.setConfig(params);

    // Execute POST
    HttpResponse response = client.execute(postReq, IhcConnectionPool.getInstance().getHttpContext());

    String resp = EntityUtils.toString(response.getEntity());
    logger.trace("Received response: {}", resp);
    return resp;
}
 
Example #4
Source File: GoHttpClientHttpInvokerRequestExecutor.java    From gocd with Apache License 2.0 6 votes vote down vote up
private void validateResponse(HttpResponse response) throws IOException {
    StatusLine status = response.getStatusLine();
    if (status.getStatusCode() >= 400) {
        String messagePrefix = String.format("The server returned status code %d. Possible reasons include:", status.getStatusCode());

        List<String> reasons = Arrays.asList(
                "This agent has been deleted from the configuration",
                "This agent is pending approval",
                "There is possibly a reverse proxy (or load balancer) that has been misconfigured. See "
                        + docsUrl("/installation/configure-reverse-proxy.html#agents-and-reverse-proxies") +
                        " for details."
        );

        String delimiter = "\n   - ";
        throw new ClientProtocolException(messagePrefix + delimiter + String.join(delimiter, reasons));
    }
    if (status.getStatusCode() >= 300) {
        throw new NoHttpResponseException("Did not receive successful HTTP response: status code = " + status.getStatusCode() + ", status message = [" + status.getReasonPhrase() + "]");
    }

}
 
Example #5
Source File: HttpEngine.java    From letv with Apache License 2.0 6 votes vote down vote up
private HttpEngine() {
    this.mDefaultHttpClient = null;
    this.mDefaultHttpClient = createHttpClient();
    this.mDefaultHttpClient.setHttpRequestRetryHandler(new HttpRequestRetryHandler() {
        public boolean retryRequest(IOException exception, int executionCount, HttpContext context) {
            if (DataStatistics.getInstance().isDebug()) {
                Log.d(DataStatistics.TAG, exception.getClass() + NetworkUtils.DELIMITER_COLON + exception.getMessage() + ",executionCount:" + executionCount);
            }
            if (executionCount >= 3) {
                return false;
            }
            if (exception instanceof NoHttpResponseException) {
                return true;
            }
            if (exception instanceof ClientProtocolException) {
                return true;
            }
            return false;
        }
    });
}
 
Example #6
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 #7
Source File: SimpleHttpFetcher.java    From ache with Apache License 2.0 6 votes vote down vote up
@Override
public boolean retryRequest(IOException exception, int executionCount, HttpContext context) {
    if (LOGGER.isTraceEnabled()) {
        LOGGER.trace("Decide about retry #" + executionCount + " for exception " + exception.getMessage());
    }

    if (executionCount >= _maxRetryCount) {
        // Do not retry if over max retry count
        return false;
    } else if (exception instanceof NoHttpResponseException) {
        // Retry if the server dropped connection on us
        return true;
    } else if (exception instanceof SSLHandshakeException) {
        // Do not retry on SSL handshake exception
        return false;
    }

    HttpRequest request = (HttpRequest) context.getAttribute(HttpCoreContext.HTTP_REQUEST);
    boolean idempotent = !(request instanceof HttpEntityEnclosingRequest);
    // Retry if the request is considered idempotent
    return idempotent;
}
 
Example #8
Source File: HttpPartitionOnCommitTest.java    From lucene-solr with Apache License 2.0 6 votes vote down vote up
protected void sendCommitWithRetry(Replica replica) throws Exception {
  String replicaCoreUrl = replica.getCoreUrl();
  log.info("Sending commit request to: {}", replicaCoreUrl);
  final RTimer timer = new RTimer();
  try (HttpSolrClient client = getHttpSolrClient(replicaCoreUrl)) {
    try {
      client.commit();

      if (log.isInfoEnabled()) {
        log.info("Sent commit request to {} OK, took {}ms", replicaCoreUrl, timer.getTime());
      }
    } catch (Exception exc) {
      Throwable rootCause = SolrException.getRootCause(exc);
      if (rootCause instanceof NoHttpResponseException) {
        log.warn("No HTTP response from sending commit request to {}; will re-try after waiting 3 seconds", replicaCoreUrl);
        Thread.sleep(3000);
        client.commit();
        log.info("Second attempt at sending commit to {} succeeded", replicaCoreUrl);
      } else {
        throw exc;
      }
    }
  }
}
 
Example #9
Source File: HttpProtocolParent.java    From dtsopensource 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 #10
Source File: VerifyResponseSenderExceptionBehaviorComponentTest.java    From riposte with Apache License 2.0 5 votes vote down vote up
private void verifyConnectionClosedException(Throwable ex) {
    boolean isNoHttpResponseEx = (ex instanceof NoHttpResponseException);
    boolean isSocketExForConnectionReset =
        (ex instanceof SocketException) && (ex.getMessage().equals("Connection reset"));

    assertThat(isNoHttpResponseEx || isSocketExForConnectionReset)
        .withFailMessage("Expected a NoHttpResponseException, or a SocketException with message "
                         + "'Connection reset', but instead found: " + ex.toString()
        )
        .isTrue();
}
 
Example #11
Source File: HCB.java    From httpclientutil with Apache License 2.0 5 votes vote down vote up
/**
 * 重试(如果请求是幂等的,就再次尝试)
 * 
 * @param tryTimes						重试次数
 * @param retryWhenInterruptedIO		连接拒绝时,是否重试
 * @return	返回当前对象
 */
public HCB retry(final int tryTimes, final boolean retryWhenInterruptedIO){
	// 请求重试处理
    HttpRequestRetryHandler httpRequestRetryHandler = new HttpRequestRetryHandler() {
        public boolean retryRequest(IOException exception, int executionCount, HttpContext context) {
            if (executionCount >= tryTimes) {// 如果已经重试了n次,就放弃
                return false;
            }
            if (exception instanceof NoHttpResponseException) {// 如果服务器丢掉了连接,那么就重试
                return true;
            }
            if (exception instanceof SSLHandshakeException) {// 不要重试SSL握手异常
                return false;
            }
            if (exception instanceof InterruptedIOException) {// 超时
                //return false;
                return retryWhenInterruptedIO;
            }
            if (exception instanceof UnknownHostException) {// 目标服务器不可达
                return true;
            }
            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;
        }
    };
    this.setRetryHandler(httpRequestRetryHandler);
    return this;
}
 
Example #12
Source File: HttpChannelizerIntegrateTest.java    From tinkerpop with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldBreakOnInvalidAuthenticationHandler() throws Exception {
    final CombinedTestClient client =  new CombinedTestClient(getProtocol());
    try {
        client.sendAndAssert("2+2", 4);
        Assert.fail("An exception should be thrown with an invalid authentication handler");
    } catch (NoHttpResponseException | SocketException e) {
    } finally {
        client.close();
    }
}
 
Example #13
Source File: BasicAuditlogTest.java    From deprecated-security-advanced-modules with Apache License 2.0 5 votes vote down vote up
@Test
public void testSSLPlainText() throws Exception {
//if this fails permanently look in the logs for an abstract method error or method not found error.
//needs proper ssl plugin version

    Settings additionalSettings = Settings.builder()
            .put("opendistro_security.ssl.http.enabled",true)
            .put("opendistro_security.ssl.http.keystore_filepath", FileHelper.getAbsoluteFilePathFromClassPath("auditlog/node-0-keystore.jks"))
            .put("opendistro_security.ssl.http.truststore_filepath", FileHelper.getAbsoluteFilePathFromClassPath("auditlog/truststore.jks"))
            .put("opendistro_security.audit.type", TestAuditlogImpl.class.getName())
            .put(ConfigConstants.OPENDISTRO_SECURITY_AUDIT_CONFIG_DISABLED_TRANSPORT_CATEGORIES, "NONE")
            .put(ConfigConstants.OPENDISTRO_SECURITY_AUDIT_CONFIG_DISABLED_REST_CATEGORIES, "NONE")
            .put("opendistro_security.audit.threadpool.size", 0)
            .build();

    setup(additionalSettings);
    TestAuditlogImpl.clear();

    try {
        nonSslRestHelper().executeGetRequest("_search", encodeBasicHeader("admin", "admin"));
        Assert.fail();
    } catch (NoHttpResponseException e) {
        //expected
    }

    Thread.sleep(1500);
    System.out.println(TestAuditlogImpl.sb.toString());
    Assert.assertFalse(TestAuditlogImpl.messages.isEmpty());
    Assert.assertTrue(TestAuditlogImpl.sb.toString().contains("SSL_EXCEPTION"));
    Assert.assertTrue(TestAuditlogImpl.sb.toString().contains("exception_stacktrace"));
    Assert.assertTrue(TestAuditlogImpl.sb.toString().contains("not an SSL/TLS record"));
    Assert.assertTrue(validateMsgs(TestAuditlogImpl.messages));
}
 
Example #14
Source File: SolrCLI.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
/**
 * Determine if a request to Solr failed due to a communication error,
 * which is generally retry-able.
 */
public static boolean checkCommunicationError(Exception exc) {
  Throwable rootCause = SolrException.getRootCause(exc);
  boolean wasCommError =
      (rootCause instanceof ConnectException ||
          rootCause instanceof ConnectTimeoutException ||
          rootCause instanceof NoHttpResponseException ||
          rootCause instanceof SocketException);
  return wasCommError;
}
 
Example #15
Source File: WiremockServerApplicationTests.java    From spring-cloud-contract with Apache License 2.0 5 votes vote down vote up
@Test
public void emptyResponse() throws Exception {
	wiremock.stubFor(get(urlEqualTo("/resource"))
			.willReturn(aResponse().withFault(Fault.EMPTY_RESPONSE)));

	assertThatThrownBy(() -> this.service.go()).hasCauseInstanceOf(NoHttpResponseException.class);
}
 
Example #16
Source File: WiremockServerApplicationTests.java    From spring-cloud-contract with Apache License 2.0 5 votes vote down vote up
@Test
public void emptyResponse() throws Exception {
	wiremock.stubFor(get(urlEqualTo("/resource"))
			.willReturn(aResponse().withFault(Fault.EMPTY_RESPONSE)));

	assertThatThrownBy(() -> this.service.go()).hasCauseInstanceOf(NoHttpResponseException.class);
}
 
Example #17
Source File: HttpClientTools.java    From lavaplayer with Apache License 2.0 5 votes vote down vote up
@Override
public boolean retryRequest(IOException exception, int executionCount, HttpContext context) {
  boolean retry = super.retryRequest(exception, executionCount, context);

  if (!retry && exception instanceof NoHttpResponseException && executionCount < 5) {
    return true;
  } else {
    return retry;
  }
}
 
Example #18
Source File: ConnectionException.java    From vespa with Apache License 2.0 5 votes vote down vote up
static boolean isKnownConnectionException(Throwable t) {
    for (; t != null; t = t.getCause()) {
        if (t instanceof SocketException ||
                t instanceof SocketTimeoutException ||
                t instanceof NoHttpResponseException ||
                t instanceof EOFException)
            return true;
    }

    return false;
}
 
Example #19
Source File: NettyIT.java    From glowroot with Apache License 2.0 5 votes vote down vote up
@Override
public void executeApp() throws Exception {
    int port = getAvailablePort();
    HttpServer server = new HttpServer(port);
    CloseableHttpClient httpClient = HttpClientBuilder.create()
            .disableAutomaticRetries()
            .build();
    HttpGet httpGet = new HttpGet("http://localhost:" + port + "/exception");
    try {
        httpClient.execute(httpGet);
    } catch (NoHttpResponseException e) {
    }
    server.close();
}
 
Example #20
Source File: SecureJettyServiceTest.java    From attic-polygene-java with Apache License 2.0 5 votes vote down vote up
@Test( expected = NoHttpResponseException.class )
// This test exists for demonstration purpose only, it do not test usefull things but it's on purpose
public void testNoSSL()
    throws IOException
{
    HttpGet get = new HttpGet( "http://127.0.0.1:" + httpsPort + "/hello" );
    defaultHttpClient.execute( get );
    fail( "We could reach the HTTPS connector using a HTTP url, that's no good" );
}
 
Example #21
Source File: Neo4jIT.java    From baleen with Apache License 2.0 5 votes vote down vote up
private void setPassword(String rootUrl) throws IOException, ClientProtocolException {
  HttpClient client = createClient("neo4j");

  RetryPolicy retryPolicy =
      new RetryPolicy()
          .retryOn(NoHttpResponseException.class)
          .withDelay(1, TimeUnit.SECONDS)
          .withMaxRetries(3);

  Failsafe.with(retryPolicy).run(() -> callSetPassword(rootUrl, client));
}
 
Example #22
Source File: HttpComponentsHttpInvokerRequestExecutor.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
/**
 * Validate the given response as contained in the HttpPost object,
 * throwing an exception if it does not correspond to a successful HTTP response.
 * <p>Default implementation rejects any HTTP status code beyond 2xx, to avoid
 * parsing the response body and trying to deserialize from a corrupted stream.
 * @param config the HTTP invoker configuration that specifies the target service
 * @param response the resulting HttpResponse to validate
 * @throws java.io.IOException if validation failed
 */
protected void validateResponse(HttpInvokerClientConfiguration config, HttpResponse response)
		throws IOException {

	StatusLine status = response.getStatusLine();
	if (status.getStatusCode() >= 300) {
		throw new NoHttpResponseException(
				"Did not receive successful HTTP response: status code = " + status.getStatusCode() +
				", status message = [" + status.getReasonPhrase() + "]");
	}
}
 
Example #23
Source File: NettyIT.java    From glowroot with Apache License 2.0 5 votes vote down vote up
@Override
public void executeApp() throws Exception {
    int port = getAvailablePort();
    HttpServer server = new HttpServer(port);
    CloseableHttpClient httpClient = HttpClientBuilder.create()
            .disableAutomaticRetries()
            .build();
    HttpGet httpGet = new HttpGet("http://localhost:" + port + "/exception");
    try {
        httpClient.execute(httpGet);
    } catch (NoHttpResponseException e) {
    }
    server.close();
}
 
Example #24
Source File: AvaticaCommonsHttpClientImplTest.java    From calcite-avatica with Apache License 2.0 5 votes vote down vote up
@Test public void testRetryOnMissingHttpResponse() throws Exception {
  final byte[] requestBytes = "fake_request".getBytes(UTF_8);
  final CloseableHttpResponse badResponse = mock(CloseableHttpResponse.class);
  final CloseableHttpResponse goodResponse = mock(CloseableHttpResponse.class);
  final StatusLine badStatusLine = mock(StatusLine.class);
  final StatusLine goodStatusLine = mock(StatusLine.class);
  final StringEntity responseEntity = new StringEntity("success");
  final Answer<CloseableHttpResponse> failThenSucceed = new Answer<CloseableHttpResponse>() {
    private int iteration = 0;
    @Override public CloseableHttpResponse answer(InvocationOnMock invocation) throws Throwable {
      iteration++;
      if (1 == iteration) {
        throw new NoHttpResponseException("The server didn't respond!");
      } else {
        return goodResponse;
      }
    }
  };

  final AvaticaCommonsHttpClientImpl client = mock(AvaticaCommonsHttpClientImpl.class);

  when(client.send(any(byte[].class))).thenCallRealMethod();
  when(client.execute(any(HttpPost.class), any(HttpClientContext.class))).then(failThenSucceed);

  when(badResponse.getStatusLine()).thenReturn(badStatusLine);
  when(badStatusLine.getStatusCode()).thenReturn(HttpURLConnection.HTTP_UNAVAILABLE);

  when(goodResponse.getStatusLine()).thenReturn(goodStatusLine);
  when(goodStatusLine.getStatusCode()).thenReturn(HttpURLConnection.HTTP_OK);
  when(goodResponse.getEntity()).thenReturn(responseEntity);

  byte[] responseBytes = client.send(requestBytes);
  assertEquals("success", new String(responseBytes, UTF_8));
}
 
Example #25
Source File: AbortNonPrefixedRequestFilterTest.java    From joal with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldHaveNoResponseFromUnprefixedRequest() {
    try {
        final ResponseEntity<String> response = this.restTemplate.getForEntity(
                "http://localhost:" + port + "/hello",
                String.class
        );
        fail("shouldn't have had a response");
    } catch (final ResourceAccessException e) {
        assertThat(e).hasCauseInstanceOf(NoHttpResponseException.class);
    }
}
 
Example #26
Source File: HttpRetryHandler.java    From android-lite-http with Apache License 2.0 5 votes vote down vote up
/**
 * @param retrySleepTimeMS        if the network is unstable, wait retrySleepTimeMS then start retry.
 * @param requestSentRetryEnabled true if it's OK to retry requests that have been sent
 */
public HttpRetryHandler(int retrySleepTimeMS, boolean requestSentRetryEnabled) {
    super(0, requestSentRetryEnabled);
    this.retrySleepTimeMS = retrySleepTimeMS;
    exceptionWhitelist.add(NoHttpResponseException.class);
    exceptionWhitelist.add(SocketException.class);
    exceptionWhitelist.add(SocketTimeoutException.class);
    exceptionWhitelist.add(ConnectTimeoutException.class);

    exceptionBlacklist.add(UnknownHostException.class);
    exceptionBlacklist.add(FileNotFoundException.class);
    exceptionBlacklist.add(SSLException.class);
    exceptionBlacklist.add(ConnectException.class);
}
 
Example #27
Source File: RetryHandler.java    From ProxyPool 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 #28
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 #29
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 #30
Source File: BrowserMobProxyHandler.java    From odo with Apache License 2.0 5 votes vote down vote up
private static void reportError(Exception e, URL url, HttpResponse response) {
    FirefoxErrorContent error = FirefoxErrorContent.GENERIC;
    if (e instanceof UnknownHostException) {
        error = FirefoxErrorContent.DNS_NOT_FOUND;
    } else if (e instanceof ConnectException) {
        error = FirefoxErrorContent.CONN_FAILURE;
    } else if (e instanceof ConnectTimeoutException) {
        error = FirefoxErrorContent.NET_TIMEOUT;
    } else if (e instanceof NoHttpResponseException) {
        error = FirefoxErrorContent.NET_RESET;
    } else if (e instanceof EOFException) {
        error = FirefoxErrorContent.NET_INTERRUPT;
    } else if (e instanceof IllegalArgumentException && e.getMessage().startsWith("Host name may not be null")) {
        error = FirefoxErrorContent.DNS_NOT_FOUND;
    } else if (e instanceof BadURIException) {
        error = FirefoxErrorContent.MALFORMED_URI;
    } else if (e instanceof SSLProtocolException) {
        return;
    }

    String shortDesc = String.format(error.getShortDesc(), url.getHost());
    String text = String.format(FirefoxErrorConstants.ERROR_PAGE, error.getTitle(), shortDesc, error.getLongDesc());

    try {
        response.setStatus(HttpResponse.__502_Bad_Gateway);
        response.setContentLength(text.length());
        response.getOutputStream().write(text.getBytes());
    } catch (IOException e1) {
        LOG.warn("IOException while trying to report an HTTP error");
    }
}