當前位置: 首頁>>代碼示例>>Java>>正文


Java HttpHostConnectException類代碼示例

本文整理匯總了Java中org.apache.http.conn.HttpHostConnectException的典型用法代碼示例。如果您正苦於以下問題:Java HttpHostConnectException類的具體用法?Java HttpHostConnectException怎麽用?Java HttpHostConnectException使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。


HttpHostConnectException類屬於org.apache.http.conn包,在下文中一共展示了HttpHostConnectException類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。

示例1: doPost

import org.apache.http.conn.HttpHostConnectException; //導入依賴的package包/類
public static String doPost(String url, String json) throws Exception {
    try {
        CloseableHttpClient client = getHttpClient(url);
        HttpPost post = new HttpPost(url);
        config(post);
        logger.info("====> Executing request: " + post.getRequestLine());
        if (!StringUtils.isEmpty(json)) {
            StringEntity s = new StringEntity(json, "UTF-8");
            s.setContentEncoding("UTF-8");
            s.setContentType("application/json");
            post.setEntity(s);
        }
        String responseBody = client.execute(post, getStringResponseHandler());
        logger.info("====> Getting response from request " + post.getRequestLine() + " The responseBody: " + responseBody);
        return responseBody;
    } catch (Exception e) {
        if (e instanceof HttpHostConnectException || e.getCause() instanceof ConnectException) {
            throw new ConnectException("====> 連接服務器" + url + "失敗: " + e.getMessage());
        }
        logger.error("====> HttpRequestUtil.doPost: " + e.getMessage(), e);
    }
    return null;
}
 
開發者ID:Evan1120,項目名稱:wechat-api-java,代碼行數:24,代碼來源:HttpRequestUtil.java

示例2: execute

import org.apache.http.conn.HttpHostConnectException; //導入依賴的package包/類
public CloseableHttpResponse execute() {
    CloseableHttpResponse response;
    try {
        response = closeableHttpClient.execute(httpRequestBase, context);
    } catch (SocketTimeoutException ste) {
        throw new RuntimeException("Socket timeout: " + ste.getMessage(), ste);
    } catch (HttpHostConnectException connectEx) {
        throw new RuntimeException("Connection error: " + connectEx.getMessage(), connectEx);
    } catch (IOException e) {
        throw new RuntimeException("Error while executing http request: " + e.getMessage(), e);
    }
    return response;
}
 
開發者ID:CloudSlang,項目名稱:cs-actions,代碼行數:14,代碼來源:HttpClientExecutor.java

示例3: doGet

import org.apache.http.conn.HttpHostConnectException; //導入依賴的package包/類
public static String doGet(String url) throws Exception {
    try {
        CloseableHttpClient client = getHttpClient(url);
        HttpGet httpget = new HttpGet(url);
        config(httpget);
        logger.info("====> Executing request: " + httpget.getRequestLine());
        String responseBody = client.execute(httpget, getStringResponseHandler());
        logger.info("====> Getting response from request " + httpget.getRequestLine() + " The responseBody: " + responseBody);
        return responseBody;
    } catch (Exception e) {
        if (e instanceof HttpHostConnectException || e.getCause() instanceof ConnectException) {
            throw e;
        }
        logger.error("HttpRequestUtil.doGet: " + e.getMessage());
    }
    return null;
}
 
開發者ID:Evan1120,項目名稱:wechat-api-java,代碼行數:18,代碼來源:HttpRequestUtil.java

示例4: waitForServerReady

import org.apache.http.conn.HttpHostConnectException; //導入依賴的package包/類
/**
 * Wait for the server is ready.
 */
private void waitForServerReady() throws IOException, InterruptedException {
	final HttpGet httpget = new HttpGet(getPingUri());
	HttpResponse response = new BasicHttpResponse(new BasicStatusLine(HttpVersion.HTTP_1_1, HttpStatus.SC_NOT_FOUND, ""));
	int counter = 0;
	while (true) {
		try {
			response = httpclient.execute(httpget);
			final int status = response.getStatusLine().getStatusCode();
			if (status == HttpStatus.SC_OK) {
				break;
			}
			checkRetries(counter);
		} catch (final HttpHostConnectException ex) { // NOSONAR - Wait, and check later
			log.info("Check failed, retrying...");
			checkRetries(counter);
		} finally {
			EntityUtils.consume(response.getEntity());
		}
		counter++;
	}
}
 
開發者ID:ligoj,項目名稱:bootstrap,代碼行數:25,代碼來源:AbstractRestTest.java

示例5: testConnectFailure

import org.apache.http.conn.HttpHostConnectException; //導入依賴的package包/類
@Test(expected=HttpHostConnectException.class)
public void testConnectFailure() throws Exception {
    final HttpContext context = new BasicHttpContext();
    final HttpHost host = new HttpHost("somehost");
    final InetAddress ip1 = InetAddress.getByAddress(new byte[] {10, 0, 0, 1});
    final InetAddress ip2 = InetAddress.getByAddress(new byte[] {10, 0, 0, 2});

    Mockito.when(dnsResolver.resolve("somehost")).thenReturn(new InetAddress[] { ip1, ip2 });
    Mockito.when(socketFactoryRegistry.lookup("http")).thenReturn(plainSocketFactory);
    Mockito.when(schemePortResolver.resolve(host)).thenReturn(80);
    Mockito.when(plainSocketFactory.createSocket(Mockito.<HttpContext>any())).thenReturn(socket);
    Mockito.when(plainSocketFactory.connectSocket(
            Mockito.anyInt(),
            Mockito.<Socket>any(),
            Mockito.<HttpHost>any(),
            Mockito.<InetSocketAddress>any(),
            Mockito.<InetSocketAddress>any(),
            Mockito.<HttpContext>any())).thenThrow(new ConnectException());

    connectionOperator.connect(conn, host, null, 1000, SocketConfig.DEFAULT, context);
}
 
開發者ID:MyPureCloud,項目名稱:purecloud-iot,代碼行數:22,代碼來源:TestHttpClientConnectionOperator.java

示例6: getRedirectUrl

import org.apache.http.conn.HttpHostConnectException; //導入依賴的package包/類
public String getRedirectUrl() {
    StringBuilder authUrl = new StringBuilder(ServiceAuthConstants.AUTH_SERVICE_URL.get());
    authUrl.append("/redirectUrl");

    HttpResponse response;
    try {
        Request temp = Request.Get(authUrl.toString()).addHeader(ServiceAuthConstants.ACCEPT, ServiceAuthConstants.APPLICATION_JSON);
        response = temp.execute().returnResponse();
        int statusCode = response.getStatusLine().getStatusCode();
        if(statusCode >= 300) {
            log.error("Got error from Auth service. statusCode: {}", statusCode);
            return "";
        }
        Map<String, Object> jsonData = jsonMapper.readValue(response.getEntity().getContent());
        if( jsonData != null && !jsonData.isEmpty()) {
            if (jsonData.containsKey("redirectUrl")) {
                return (String)jsonData.get("redirectUrl");
            }
        }
    } catch(HttpHostConnectException ex) {
        log.error("Auth Service not reachable at [{}]", ServiceAuthConstants.AUTH_SERVICE_URL);
    } catch (IOException e) {
        log.error("Failed to get the redirectUrl from Auth Service.", e);
    }
    return "";
}
 
開發者ID:rancher,項目名稱:cattle,代碼行數:27,代碼來源:ExternalServiceAuthProvider.java

示例7: testServerStopsSpecifyPort

import org.apache.http.conn.HttpHostConnectException; //導入依賴的package包/類
@Test(expected = HttpHostConnectException.class)
public void testServerStopsSpecifyPort() throws Exception {
    int port = getFreePort();

    JettyServer jettyServer = new JettyServer();
    jettyServer.start(port);

    HttpClient httpClient = new DefaultHttpClient();
    HttpGet workflowListGet = new HttpGet("http://localhost:" + port);
    HttpResponse response = httpClient.execute(workflowListGet);

    Assert.assertEquals(response.getStatusLine().getStatusCode(), 403);
    EntityUtils.consume(response.getEntity());
    jettyServer.stop();

    httpClient.execute(workflowListGet);
}
 
開發者ID:collectivemedia,項目名稱:celos,代碼行數:18,代碼來源:JettyServerTest.java

示例8: check

import org.apache.http.conn.HttpHostConnectException; //導入依賴的package包/類
public boolean check() throws InterruptedException {
    try {
        HttpResponse<String> health = Unirest.get(url + "/admin/healthcheck")
                .basicAuth("test", "test")
                .asString();

        if (health.getStatus() == 200) {
            log.info("Healthy with {}", health.getBody());
            return true;
        } else {
            log.error("Unhealthy with {}", health.getBody());
            return false;
        }
    } catch (UnirestException e) {
        if (e.getCause() instanceof HttpHostConnectException && duration < maxDuration) {
            log.info("Unable to connect, retrying...");
            duration = duration + DELAY;
            Thread.sleep(TimeUnit.SECONDS.toMillis(DELAY));
            return check();
        }
        log.error("Unable to connect.", e);
        return false;
    }
}
 
開發者ID:Lugribossk,項目名稱:dropwizard-experiment,代碼行數:25,代碼來源:HealthChecker.java

示例9: setException

import org.apache.http.conn.HttpHostConnectException; //導入依賴的package包/類
/**
 * 異常信息統一處理
 * 
 * @param resObj 響應對象
 * @param ec 異常�?
 * @param optionStatus 自定義狀態編�?
 * @param optionErrorMessage 自定義錯誤信�?
 */
private void setException(ResponseObject resObj, Exception ec,Integer optionStatus,String optionErrorMessage) {
	String errorMessage="";
	resObj.setStatus(optionStatus);//鏈接超時代碼
	if(ec instanceof UnknownHostException){
		errorMessage=ec.getMessage();
	}
	if(ec instanceof ConnectTimeoutException){
		errorMessage=ec.getMessage();
	}
	if(ec instanceof HttpHostConnectException){
		errorMessage=ec.getMessage();
	}
	resObj.setErrorMessage(errorMessage);
	resObj.setOptionErrorMessage(optionErrorMessage);
}
 
開發者ID:zubryan,項目名稱:CloudM,代碼行數:24,代碼來源:CommonInvoker.java

示例10: stop

import org.apache.http.conn.HttpHostConnectException; //導入依賴的package包/類
@Test
public void stop() throws Exception {
    storage.stop();
    try {
        // Should not respond after stop
        status();
    } catch (SocketTimeoutException | HttpHostConnectException e) {
        // Do nothing
    }
}
 
開發者ID:polis-mail-ru,項目名稱:2017-highload-kv,代碼行數:11,代碼來源:StartStopTest.java

示例11: updateSecureConnection

import org.apache.http.conn.HttpHostConnectException; //導入依賴的package包/類
public void updateSecureConnection(
        final OperatedClientConnection conn,
        final HttpHost target,
        final HttpContext context,
        final HttpParams params) throws IOException {
    if (conn == null) {
        throw new IllegalArgumentException("Connection may not be null");
    }
    if (target == null) {
        throw new IllegalArgumentException("Target host may not be null");
    }
    if (params == null) {
        throw new IllegalArgumentException("Parameters may not be null");
    }
    if (!conn.isOpen()) {
        throw new IllegalStateException("Connection must be open");
    }

    final Scheme schm = schemeRegistry.getScheme(target.getSchemeName());
    if (!(schm.getSchemeSocketFactory() instanceof SchemeLayeredSocketFactory)) {
        throw new IllegalArgumentException
            ("Target scheme (" + schm.getName() +
             ") must have layered socket factory.");
    }

    SchemeLayeredSocketFactory lsf = (SchemeLayeredSocketFactory) schm.getSchemeSocketFactory();
    Socket sock;
    try {
        sock = lsf.createLayeredSocket(
                conn.getSocket(), target.getHostName(), target.getPort(), params);
    } catch (ConnectException ex) {
        throw new HttpHostConnectException(target, ex);
    }
    prepareSocket(sock, context, params);
    conn.update(sock, target, lsf.isSecure(sock), params);
}
 
開發者ID:lamsfoundation,項目名稱:lams,代碼行數:37,代碼來源:DefaultClientConnectionOperator.java

示例12: testStartRestServerKo3

import org.apache.http.conn.HttpHostConnectException; //導入依賴的package包/類
@Test(expected = IllegalStateException.class)
public void testStartRestServerKo3() throws IOException {
	retries = 0;
	httpclient = Mockito.mock(CloseableHttpClient.class);
	Mockito.when(httpclient.execute(ArgumentMatchers.any(HttpGet.class))).thenThrow(new HttpHostConnectException(null, null, new InetAddress[0]));
	startRestServer("log4j2.json");
}
 
開發者ID:ligoj,項目名稱:bootstrap,代碼行數:8,代碼來源:TestAbstractRestTest.java

示例13: canRetry

import org.apache.http.conn.HttpHostConnectException; //導入依賴的package包/類
private boolean canRetry(Throwable e, HttpMethod method) {
  Throwable nestedException = e.getCause();
  if (method == HttpMethod.GET) {
    return nestedException instanceof SocketTimeoutException
           || nestedException instanceof HttpHostConnectException
           || nestedException instanceof ConnectTimeoutException;
  } else {
    return nestedException instanceof HttpHostConnectException
           || nestedException instanceof ConnectTimeoutException;
  }
}
 
開發者ID:dewey-its,項目名稱:apollo-custom,代碼行數:12,代碼來源:RetryableRestTemplate.java

示例14: init

import org.apache.http.conn.HttpHostConnectException; //導入依賴的package包/類
@Before
public void init() {
  socketTimeoutException.initCause(new SocketTimeoutException());

  httpHostConnectException
      .initCause(new HttpHostConnectException(new ConnectTimeoutException(), new HttpHost(serviceOne, 80)));
  connectTimeoutException.initCause(new ConnectTimeoutException());
}
 
開發者ID:dewey-its,項目名稱:apollo-custom,代碼行數:9,代碼來源:RetryableRestTemplateTest.java

示例15: collectData

import org.apache.http.conn.HttpHostConnectException; //導入依賴的package包/類
@Override
protected void collectData(Gson gson, String user, List<String> subscriptions) {
    Map<String, String> subscriptionData = new HashMap<>();
    for (String url : subscriptions) {
        try (CloseableHttpClient httpClient = HttpClientHelper.buildHttpClient()) {
            HttpUriRequest query = RequestBuilder.get()
                    .setUri(url)
                    .build();
            try (CloseableHttpResponse queryResponse = httpClient.execute(query)) {
                HttpEntity entity = queryResponse.getEntity();
                if (entity != null) {
                    String data = EntityUtils.toString(entity);
                    if (data != null && data.length() > 0) {
                        if (data.contains("www.dnsrsearch.com")) {
                            subscriptionData.put(url, "not found");
                        } else {
                            subscriptionData.put(url, "up");
                        }
                    } else {
                        subscriptionData.put(url, "down");
                    }
                } else {
                    subscriptionData.put(url, "down");
                }
            }
        } catch (HttpHostConnectException hhce) {
            subscriptionData.put(url, "down");
        } catch (Throwable throwable) {
            logger.error(throwable.getMessage(), throwable);
            subscriptionData.put(url, "down");
        }
    }

    DataResponse response = new DataResponse();
    response.setType("UpDownResponse");
    response.setId(user);
    response.setResult(MessageConstants.SUCCESS);
    response.setSubscriptionData(subscriptionData);
    responseQueue.add(gson.toJson(response));
}
 
開發者ID:jwboardman,項目名稱:whirlpool,代碼行數:41,代碼來源:UpDownService.java


注:本文中的org.apache.http.conn.HttpHostConnectException類示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。