当前位置: 首页>>代码示例>>Java>>正文


Java ConnectException类代码示例

本文整理汇总了Java中java.net.ConnectException的典型用法代码示例。如果您正苦于以下问题:Java ConnectException类的具体用法?Java ConnectException怎么用?Java ConnectException使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


ConnectException类属于java.net包,在下文中一共展示了ConnectException类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: onError

import java.net.ConnectException; //导入依赖的package包/类
@Override
public void onError(Throwable e) {
    if(subscriberOnListener != null && context != null)
    {
        if (e instanceof SocketTimeoutException) {
            subscriberOnListener.onError(-1001, "网络超时,请检查您的网络状态");
        } else if (e instanceof ConnectException) {
            subscriberOnListener.onError(-1002, "网络链接中断,请检查您的网络状态");
        } else if(e instanceof ExceptionApi){
            subscriberOnListener.onError(((ExceptionApi)e).getCode(), ((ExceptionApi)e).getMsg());
        }
        else
        {
            subscriberOnListener.onError(-1003, "未知错误:" + e.getMessage());
        }
    }
    else
    {
        if(disposable != null && !disposable.isDisposed())
            disposable.dispose();
    }
}
 
开发者ID:wanliyang1990,项目名称:AppServiceRestFul,代码行数:23,代码来源:HttpSubscriber.java

示例2: doPost

import java.net.ConnectException; //导入依赖的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

示例3: test_NoUser

import java.net.ConnectException; //导入依赖的package包/类
@Ignore
@Test(expected = ConnectException.class)
public void test_NoUser() throws Throwable {
    ServiceInstance instance = new ServiceInstance();
    ArrayList<InstanceParameter> params = new ArrayList<InstanceParameter>();
    params.add(PUBLIC_IP);
    params.add(WSDL);
    params.add(PROTOCOL);
    params.add(PORT);
    instance.setInstanceParameters(params);
    try {
        getInstance(instance);
    } catch (BadResultException e) {
        throw e.getCause();
    }
}
 
开发者ID:servicecatalog,项目名称:oscm,代码行数:17,代码来源:ProductProvisioningServiceFactoryBeanTest.java

示例4: connectSocket

import java.net.ConnectException; //导入依赖的package包/类
/** Does all the work necessary to build a full HTTP or HTTPS connection on a raw socket. */
private void connectSocket(int connectTimeout, int readTimeout) throws IOException {
  Proxy proxy = route.proxy();
  Address address = route.address();

  rawSocket = proxy.type() == Proxy.Type.DIRECT || proxy.type() == Proxy.Type.HTTP
      ? address.socketFactory().createSocket()
      : new Socket(proxy);

  rawSocket.setSoTimeout(readTimeout);
  try {
    Platform.get().connectSocket(rawSocket, route.socketAddress(), connectTimeout);
  } catch (ConnectException e) {
    ConnectException ce = new ConnectException("Failed to connect to " + route.socketAddress());
    ce.initCause(e);
    throw ce;
  }
  source = Okio.buffer(Okio.source(rawSocket));
  sink = Okio.buffer(Okio.sink(rawSocket));
}
 
开发者ID:weiwenqiang,项目名称:GitHub,代码行数:21,代码来源:RealConnection.java

示例5: getKeepAlive

import java.net.ConnectException; //导入依赖的package包/类
@Test public void getKeepAlive() throws Exception {
  server.enqueue(new MockResponse().setBody("ABC"));

  // The request should work once and then fail
  HttpURLConnection connection1 = urlFactory.open(server.url("/").url());
  connection1.setReadTimeout(100);
  InputStream input = connection1.getInputStream();
  assertEquals("ABC", readAscii(input, Integer.MAX_VALUE));
  server.shutdown();
  try {
    HttpURLConnection connection2 = urlFactory.open(server.url("").url());
    connection2.setReadTimeout(100);
    connection2.getInputStream();
    fail();
  } catch (ConnectException expected) {
  }
}
 
开发者ID:weiwenqiang,项目名称:GitHub,代码行数:18,代码来源:URLConnectionTest.java

示例6: wrapException

import java.net.ConnectException; //导入依赖的package包/类
/**
 * Take an IOException and a URI, wrap it where possible with
 * something that includes the URI
 *
 * @param dest target URI
 * @param operation operation
 * @param exception the caught exception.
 * @return an exception to throw
 */
public static IOException wrapException(final String dest,
                                        final String operation,
                                        final IOException exception) {
  String action = operation + " " + dest;
  String xref = null;

  if (exception instanceof ConnectException) {
    xref = "ConnectionRefused";
  } else if (exception instanceof UnknownHostException) {
    xref = "UnknownHost";
  } else if (exception instanceof SocketTimeoutException) {
    xref = "SocketTimeout";
  } else if (exception instanceof NoRouteToHostException) {
    xref = "NoRouteToHost";
  }
  String msg = action
               + " failed on exception: "
               + exception;
  if (xref != null) {
     msg = msg + ";" + see(xref);
  }
  return wrapWithMessage(exception, msg);
}
 
开发者ID:naver,项目名称:hadoop,代码行数:33,代码来源:ExceptionDiags.java

示例7: preCreateConnections

import java.net.ConnectException; //导入依赖的package包/类
@Override
public void preCreateConnections(final int count)
throws ConnectException, IllegalArgumentException {
	if(count > 0) {
		for(int i = 0; i < count; i ++) {
			final Channel conn = connectToAnyNode();
			if(conn == null) {
				throw new ConnectException(
					"Failed to pre-create the connections to the target nodes"
				);
			}
			final String nodeAddr = conn.attr(ATTR_KEY_NODE).get();
			if(conn.isActive()) {
				final Queue<Channel> connQueue = availableConns.get(nodeAddr);
				if(connQueue != null) {
					connQueue.add(conn);
				}
			} else {
				conn.close();
			}
		}
		LOG.info("Pre-created " + count + " connections");
	} else {
		throw new IllegalArgumentException("Connection count should be > 0, but got " + count);
	}
}
 
开发者ID:akurilov,项目名称:netty-connection-pool,代码行数:27,代码来源:BasicMultiNodeConnPool.java

示例8: failed

import java.net.ConnectException; //导入依赖的package包/类
@Override
public void failed(HttpClientCallbackResult result) {

    /**
     * auto fail record
     */
    HttpAsyncException e = result.getException();

    if (e != null && ((e.getCause() instanceof java.net.ConnectException)
            && e.getCause().getMessage().indexOf("Connection refused") > -1)) {

        getLogger().err(this, "Connection[" + postURL + "] is Unavailable. ", e);

        cfm.putFailConnection(url);
        /**
         * let's retry
         */
        doHttpPost(serverAddress, subPath, data, contentType, encoding, callBack);
        return;
    }

    if (callBack != null) {
        callBack.failed(result);
    }
}
 
开发者ID:uavorg,项目名称:uavstack,代码行数:26,代码来源:AppHubBaseRestService.java

示例9: onDownload

import java.net.ConnectException; //导入依赖的package包/类
@Override
public Pair<Boolean, List<File>> onDownload(@NotNull ClassEntity[] classEntities, @NotNull File outputFolder) {
    String newUrl = null;
    try {
        newUrl = androidOnlineSearch(classEntities[0]);
    } catch (ConnectException | UnknownHostException e1) {
        if (timeoutListener != null) {
            timeoutListener.run();
        }
    } catch (Exception e) {
        Log.e(e);
    }
    if (!Utils.isEmpty(newUrl)) {
        for (ClassEntity entity : classEntities) {
            entity.setDownloadUrl(newUrl);
        }
        Log.debug("SearchDownload => " + newUrl);
        return new XrefDownload().onDownload(classEntities, outputFolder);
    }
    return Pair.create(false, Collections.<File>emptyList());
}
 
开发者ID:pengwei1024,项目名称:AndroidSourceViewer,代码行数:22,代码来源:SearchDownload.java

示例10: logoutUser

import java.net.ConnectException; //导入依赖的package包/类
public String logoutUser(String saasId) throws ServletException,
        RemoteException {
    SessionServiceStub stub = new SessionServiceStub(getEndPoint(false));
    setBasicAuth(stub);
    SessionServiceStub.DeleteServiceSessionE dss = new SessionServiceStub.DeleteServiceSessionE();
    SessionServiceStub.DeleteServiceSession param = new SessionServiceStub.DeleteServiceSession();
    param.setSessionId(getSessionId(saasId));
    param.setSubscriptionKey(getSubscriptionKey(saasId));
    dss.setDeleteServiceSession(param);
    try {
        DeleteServiceSessionResponseE response = stub
                .deleteServiceSession(dss);
        return response.getDeleteServiceSessionResponse().get_return();
    } catch (AxisFault e) {
        if (port < 8185 && searchPort
                && e.getDetail() instanceof ConnectException) {
            // try again with another port
            port++;
            return logoutUser(saasId);
        }
        throw new ServletException(e);
    }
}
 
开发者ID:servicecatalog,项目名称:oscm,代码行数:24,代码来源:BssClient.java

示例11: testConnectToUnknown

import java.net.ConnectException; //导入依赖的package包/类
@Test
public void testConnectToUnknown() throws Exception {
    NetworkClient<String> client = createClient(f -> f.setConnectTimeout(Integer.MAX_VALUE));

    repeat(3, i -> {
        NetworkClientCallbackMock<String> callback = new NetworkClientCallbackMock<>();

        assertSame(NetworkClient.State.DISCONNECTED, client.state());

        try {
            client.connect(new InetSocketAddress(InetAddress.getLocalHost(), 15001), callback).get();

            fail("Error was expected");
        } catch (ExecutionException e) {
            assertTrue(e.getCause().toString(), ErrorUtils.isCausedBy(ConnectException.class, e));
        }

        assertSame(NetworkClient.State.DISCONNECTED, client.state());
        assertNull(client.remoteAddress());
        assertNull(client.localAddress());
        callback.assertConnects(0);
        callback.assertDisconnects(1);
        callback.assertErrors(1);
        callback.getErrors().forEach(e -> assertTrue(e.toString(), e instanceof ConnectException));
    });
}
 
开发者ID:hekate-io,项目名称:hekate,代码行数:27,代码来源:NetworkClientTest.java

示例12: createRemoteRcFile

import java.net.ConnectException; //导入依赖的package包/类
private static RcFile createRemoteRcFile(ExecutionEnvironment env)
        throws IOException, RcFile.FormatException, ConnectException, CancellationException, InterruptedException, ExecutionException {
    if (!ConnectionManager.getInstance().isConnectedTo(env)) {
        new Exception("WARNING: getRemoteRcFile changes connection state for " + env).printStackTrace();
        ConnectionManager.getInstance().connectTo(env);
    }
    String envText = ExecutionEnvironmentFactory.toUniqueID(env).replace(':', '-').replace('@', '-');
    String tmpName = "cnd_remote_test_rc_" + envText;
    File tmpFile = File.createTempFile(tmpName, "");
    tmpFile.deleteOnExit();
    String remoteFilePath = HostInfoUtils.getHostInfo(env).getUserDir() + "/.cnd-remote-test-rc";
    if (fileExists(env, remoteFilePath)) {
        int rc = CommonTasksSupport.downloadFile(remoteFilePath, env, tmpFile, new PrintWriter(System.err)).get();
        if (rc != 0) {
            throw new IOException("Can't download file " + remoteFilePath + " from " + env);
        }
        return RcFile.create(tmpFile);
    } else {
        return RcFile.createDummy();
    }
}
 
开发者ID:apache,项目名称:incubator-netbeans,代码行数:22,代码来源:NativeExecutionTestSupport.java

示例13: getNotFoundError

import java.net.ConnectException; //导入依赖的package包/类
private static String getNotFoundError(CoreException ce) {
    IStatus status = ce.getStatus();
    Throwable t = status.getException();
    if(t instanceof UnknownHostException ||
       // XXX maybe a different msg ?     
       t instanceof SocketTimeoutException || 
       t instanceof NoRouteToHostException ||
       t instanceof ConnectException) 
    {
        Bugzilla.LOG.log(Level.FINER, null, t);
        return NbBundle.getMessage(BugzillaExecutor.class, "MSG_HOST_NOT_FOUND");                   // NOI18N
    }
    String msg = getMessage(ce);
    if(msg != null) {
        msg = msg.trim().toLowerCase();
        if(HTTP_ERROR_NOT_FOUND.equals(msg)) {
            Bugzilla.LOG.log(Level.FINER, "returned error message [{0}]", msg);                     // NOI18N
            return NbBundle.getMessage(BugzillaExecutor.class, "MSG_HOST_NOT_FOUND");               // NOI18N
        }
    }
    return null;
}
 
开发者ID:apache,项目名称:incubator-netbeans,代码行数:23,代码来源:BugzillaExecutor.java

示例14: channelInactive

import java.net.ConnectException; //导入依赖的package包/类
@Override
public void channelInactive(ChannelHandlerContext ctx) throws Exception {
    if (metrics != null) {
        metrics.onDisconnect();
    }

    if (state == CONNECTING) {
        state = DISCONNECTED;

        ctx.fireExceptionCaught(new ConnectException("Got disconnected on handshake [channel=" + id + ']'));
    } else {
        state = DISCONNECTED;

        super.channelInactive(ctx);
    }
}
 
开发者ID:hekate-io,项目名称:hekate,代码行数:17,代码来源:NettyClientHandler.java

示例15: exceptionCaught

import java.net.ConnectException; //导入依赖的package包/类
/** Catch any exceptions, logging them and then closing the channel. */
private void exceptionCaught(Exception e) {
    PeerAddress addr = getAddress();
    String s = addr == null ? "?" : addr.toString();
    if (e instanceof ConnectException || e instanceof IOException) {
        // Short message for network errors
        log.info(s + " - " + e.getMessage());
    } else {
        log.warn(s + " - ", e);
        Thread.UncaughtExceptionHandler handler = Threading.uncaughtExceptionHandler;
        if (handler != null)
            handler.uncaughtException(Thread.currentThread(), e);
    }

    close();
}
 
开发者ID:guodroid,项目名称:okwallet,代码行数:17,代码来源:PeerSocketHandler.java


注:本文中的java.net.ConnectException类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。