网络编程常用方法


获取 host

/**
 * 获取 host
 */
public String getHost(String urlStr) {
    try {
        URI uri = new URI(urlStr);
        return uri.getHost();
    } catch (URISyntaxException e) {
        // log
    }
    return "";
}

获取 端口号

/**
 * 获取 端口号
 */
public int getPort(String urlStr) {
    try {
        URI uri = new URI(urlStr);
        int port = uri.getPort();
        if (port == -1) {
            return 80;
        }
        return port;
    } catch (URISyntaxException e) {
        // log
    }
    return -1;
}

校验URL

/**
 * 校验URL
 */
public boolean checkUrl(String urlStr) {
    if (StringUtils.isBlank(urlStr)) {
        return false;
    }
    try {
        URL url = new URL(urlStr);
        // 限制协议
        if (!url.getProtocol().startsWith("http") && !url.getProtocol().startsWith("https")) {
            return false;
        }
        // 限制环回地址
        InetAddress inetAddress = InetAddress.getByName(url.getHost());
        if (inetAddress.isLoopbackAddress()) {
            return false;
        }
    } catch (MalformedURLException e) {
        return false;
    } catch (UnknownHostException e) {
        return false;
    }
    return true;
}

如何获取本机在局域网中的IP地址?

你可能感兴趣的:(网络编程,网络)