Methods to solve Java network connection exception (ConnectException)
In Java programs, network connection exception (ConnectException) is a common error. When you use a Java program to establish a network connection to another computer or server, you may encounter a ConnectException exception. This exception is usually caused by the inability to connect to the target host. Possible reasons include the non-existence of the target host, network failure, and unopened ports.
For ConnectException exceptions, we can take a series of methods and measures to solve the problem. Several commonly used methods will be introduced below, with corresponding code examples for reference.
Code example:
String host = "example.com"; int port = 80; try { InetAddress inetAddress = InetAddress.getByName(host); boolean reachable = inetAddress.isReachable(10000); if (!reachable) { System.out.println(host + " is not reachable."); } else { System.out.println(host + " is reachable."); // 进一步进行连接操作 } } catch (UnknownHostException e) { System.out.println("Unknown host: " + host); } catch (IOException e) { e.printStackTrace(); }
Code example:
String host = "example.com"; int port = 80; try { // 禁用防火墙 Runtime.getRuntime().exec("sudo systemctl stop firewalld"); // 连接操作 Socket socket = new Socket(host, port); // 其他操作 } catch (IOException e) { e.printStackTrace(); } finally { // 恢复防火墙设置 try { Runtime.getRuntime().exec("sudo systemctl start firewalld"); } catch (IOException e) { e.printStackTrace(); } }
setSoTimeout
method to set the connection timeout. Code example:
String host = "example.com"; int port = 80; try { Socket socket = new Socket(); socket.connect(new InetSocketAddress(host, port), 10000); // 设置连接超时时间为 10 秒 // 连接成功,执行其他操作 } catch (IOException e) { e.printStackTrace(); }
Code sample (using Apache HttpClient):
String url = "https://example.com"; HttpClient client = HttpClient.newBuilder() .connectTimeout(Duration.ofSeconds(10)) .build(); HttpRequest request = HttpRequest.newBuilder() .uri(new URI(url)) .GET() .build(); HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString()); int statusCode = response.statusCode(); if (statusCode == 200) { // 连接成功,执行其他操作 } else { System.out.println("Failed to connect: " + statusCode); }
Through the above methods and sample code, you can better solve network connection exceptions in Java programs. In actual applications, select the appropriate method according to the specific situation, and perform reasonable optimization and debugging combined with the exception handling mechanism to ensure the stability and reliability of the network connection.
The above is the detailed content of Methods to solve Java network connection exception (ConnectException). For more information, please follow other related articles on the PHP Chinese website!