Java 网络操作示例


1. URI

URIJava 中用于标识统一资源的位置和标识符, 如文件、网页、电子邮件。

public void uriDemo() {
    try {
        File file = new File("src\\main\\resources\\info.txt");
        System.out.println("URI: " + file.toURI());
    } catch (Exception e) {
        e.printStackTrace();
    }
}

JDK 中除了 URI 同时还提供了 URL 专门针对网络资源,可以理解为 URI 的子集。

URL 的基本使用示例如下,通过其可以验证 URL 资源的合法性以及其基本信息:

public void urlDemo() {
    String http = "http://127.0.0.1:8080/api/user/list";
    try {
        URL url = new URL(http);
        // Get url protocol
        String protocol = url.getProtocol();
        System.out.println("Protocol: " + protocol);

        // Get url host
        String host = url.getHost();
        System.out.println("Host: " + host);

        // Get url port
        int port = url.getPort();
        System.out.println("Port: " + port);
        
        // Get url address
        String path = url.getPath();
        System.out.println("Path: " + path);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

2. IP查询

通过 InetAddress 类可以获取当前服务的 IP 地址,具体示例如下:

public void demo throws Exception {
    InetAddress localHost = InetAddress.getLocalHost();
    String host = String.valueOf(localHost);
    // Host: node102/192.168.0.103
    System.out.println("Host: " + host);
    String hostName = localHost.getHostName();
    // Host name: node103
    System.out.println("Host name: " + hostName);
    String ipAddress = localHost.getHostAddress();
    // IP: 192.168.0.103
    System.out.println("IP: " + ipAddress);
}

3. PING

通过 isReachable() 方法测试当前服务能否访问目标 IP ,作用效果类似于 PING 命令。

private boolean pingHost(String ip) {
    boolean isConnected;
    try {
        InetAddress inet = InetAddress.getByName(ip);
        isConnected = inet.isReachable(10000);
    } catch (Exception e) {
        isConnected = false;
    }
    return isConnected;
}

4. Telnet

通过 connect() 方法测试当前服务能否访问目标 IP 与端口,作用效果类似于 Telnet 命令。

private boolean telnetHost(String ip, int port) {
    boolean isConnected;
    try (Socket socket = new Socket()) {
        InetSocketAddress inet = new InetSocketAddress(ip, port);
        socket.connect(inet, 10000);
        isConnected = socket.isConnected();
    } catch (Exception e) {
        isConnected = false;
    }
    return isConnected;
}

5. API测试

通过 openConnection() 方法测试当前服务是否能正常访问,如测试 http://127.0.0.1:8080/demo 页面服务是否正常。

private boolean testUrl(String urlAddr) {
    boolean isConnected;
    try {
        URL url = new URL(urlAddr);
        HttpURLConnection oc = (HttpURLConnection) url.openConnection();
        oc.setUseCaches(false);
        oc.setConnectTimeout(10000);
        isConnected = 200 == oc.getResponseCode();
    } catch (Exception e) {
        isConnected = false;
    }
    return isConnected;
}

文章作者: 烽火戏诸诸诸侯
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 烽火戏诸诸诸侯 !
  目录