当前位置: 首页>>代码示例>>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;未经允许,请勿转载。