本文整理匯總了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();
}
}
示例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;
}
示例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();
}
}
示例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));
}
示例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) {
}
}
示例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);
}
示例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);
}
}
示例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);
}
}
示例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());
}
示例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);
}
}
示例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));
});
}
示例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();
}
}
示例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;
}
示例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);
}
}
示例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();
}