Java.Utils:網絡工具包

package com.bood.common.utils;

import org.springframework.util.MultiValueMap;
import org.springframework.web.util.UriComponentsBuilder;

import javax.net.ssl.HttpsURLConnection;
import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.*;

/**
 * 網絡工具包
 *
 * @author:bood
 * @since:2020/2/7
 */
public class NetUtils {

    public NetUtils() {
    }

    /**
     * 根據url和請求參數獲取URI
     */
    public static URI getURIwithParams(String url, MultiValueMap<String, String> params) {
        UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(url).queryParams(params);
        return builder.build().encode().toUri();
    }

    /**
     * 獲取請求中的IP
     *
     * @param request
     * @return
     */
    public static String getIpAddress(HttpServletRequest request) {
        String[] ipHeaders = {"x-forwarded-for", "Proxy-Client-IP", "WL-Proxy-Client-IP", "HTTP_CLIENT_IP", "HTTP_X_FORWARDED_FOR"};
        String[] localhostIp = {"127.0.0.1", "0:0:0:0:0:0:0:1"};
        String ip = request.getRemoteAddr();
        for (String header : ipHeaders) {
            if (ip != null && ip.length() != 0 && !"unknown".equalsIgnoreCase(ip)) {
                break;
            }
            ip = request.getHeader(header);
        }
        for (String local : localhostIp) {
            if (ip != null && ip.equals(local)) {
                try {
                    ip = InetAddress.getLocalHost().getHostAddress();
                } catch (UnknownHostException ignored) {
                }
                break;
            }
        }
        if (ip != null && ip.length() > 15 && ip.contains(",")) {
            ip = ip.substring(0, ip.indexOf(','));
        }
        return ip;
    }

    /**
     * IP轉Integer
     *
     * @param ip
     * @return
     */
    public static Integer ipToInteger(String ip) {
        String[] ips = ip.split("\\.");
        int ipFour = 0;
        for (String ip4 : ips) {
            Integer ip4a = Integer.parseInt(ip4);
            ipFour = (ipFour << 8) | ip4a;
        }
        return ipFour;
    }

    /**
     * Integer轉IP
     *
     * @param ip
     * @return
     */
    public static String IntegerToIp(Integer ip) {
        StringBuilder sb = new StringBuilder();
        for (int i = 3; i >= 0; i--) {
            int ipa = (ip >> (8 * i)) & (0xff);
            sb.append(ipa + ".");
        }
        sb.delete(sb.length() - 1, sb.length());
        return sb.toString();
    }

    /**
     * IP地址是否可達
     *
     * @param ip
     * @return boolean
     */
    public static boolean isReachable(String ip) {
        InetAddress address;
        try {
            address = InetAddress.getByName(ip);
            if (address.isReachable(5000)) {
                return true;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 判斷網址是否有效<br>
     * <b>注意</b> 對於404頁面,如果被電信或者聯通劫持了,也會返回200的狀態,這個是不準確的
     *
     * @param url URL對象
     * @return boolean
     */
    public static boolean isReachable(URL url) {

        boolean reachable = false;
        HttpURLConnection httpconn = null;
        HttpsURLConnection httpsconn = null;
        int code = 0;

        try {
            if (url.getProtocol().equals("https")) {
                httpsconn = (HttpsURLConnection) url.openConnection();
                code = httpsconn.getResponseCode();
            } else {
                httpconn = (HttpURLConnection) url.openConnection();
                code = httpconn.getResponseCode();
            }
            System.out.println(code);
            if (code == 200) {
                reachable = true;
            }
        } catch (Exception e) {
            reachable = false;
        }

        return reachable;
    }

    /**
     * 實現Ping命令
     *
     * @param ip
     * @return Ping的字符串換行使用java的換行符"\n",如果ping不同返回null
     */
    public static String ping(String ip) {
        String res = "";
        String line = null;
        try {
            Process pro = Runtime.getRuntime().exec("ping " + ip);
            BufferedReader buf = new BufferedReader(new InputStreamReader(pro.getInputStream(), "GBK"));
            while ((line = buf.readLine()) != null) {
                if (!line.equals("")) {
                    res += String.valueOf(line) + "\n";
                }
            }
        } catch (Exception e) {
            res = null;
        }
        return res;
    }

}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章