欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Java項(xiàng)目常見(jiàn)工具類(lèi)詳解

 更新時(shí)間:2021年12月24日 15:14:32   作者:LL.LEBRON  
這篇文章主要為大家總結(jié)了平時(shí)在Java項(xiàng)目中使用的工具類(lèi):JWT工具類(lèi)、MD5工具類(lèi)、視頻點(diǎn)播工具類(lèi)、公共常量工具類(lèi)、日期操作工具類(lèi)、Http客戶(hù)端工具類(lèi)和獲取IP工具類(lèi)。需要的可以參考一下

JWT工具類(lèi)

這里一共涉及四個(gè)方法:

傳入用戶(hù)信息獲得token

傳入token字符串判斷token是否存在與有效

傳入HttpServletRequest,通過(guò)獲取Header中的token判斷是否存在與有效

根據(jù)token獲取用戶(hù)id

public class JwtUtils {

    //token過(guò)期時(shí)間
    public static final long EXPIRE = 1000 * 60 * 60 * 24;
    //秘鑰
    public static final String APP_SECRET = "ukc8BDbRigUDaY6pZFfWus2jZWLPHO";

    /**
     * 獲得token
     *
     * @param id       用戶(hù)id
     * @param nickname 用戶(hù)昵稱(chēng)
     * @return
     */
    public static String getJwtToken(String id, String nickname) {

        String JwtToken = Jwts.builder()
                //設(shè)置jwt頭信息
                .setHeaderParam("typ", "JWT")
                .setHeaderParam("alg", "HS256")
                //設(shè)置分類(lèi)
                .setSubject("guli-user")
                //設(shè)置簽發(fā)時(shí)間
                .setIssuedAt(new Date())
                //設(shè)置過(guò)期時(shí)間=當(dāng)前時(shí)間+過(guò)多久過(guò)期的時(shí)間
                .setExpiration(new Date(System.currentTimeMillis() + EXPIRE))
                //設(shè)置token主體部分,存儲(chǔ)用戶(hù)信息
                .claim("id", id)
                .claim("nickname", nickname)
                //設(shè)置簽發(fā)算法+秘鑰
                .signWith(SignatureAlgorithm.HS256, APP_SECRET)
                .compact();
        return JwtToken;
    }

    /**
     * 判斷token是否存在與有效
     *
     * @param jwtToken
     * @return
     */
    public static boolean checkToken(String jwtToken) {
        if (StringUtils.isEmpty(jwtToken)) return false;
        try {
            //驗(yàn)證token是否是有效的token
            Jwts.parser().setSigningKey(APP_SECRET).parseClaimsJws(jwtToken);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    /**
     * 判斷token是否存在與有效
     *
     * @param request
     * @return
     */
    public static boolean checkToken(HttpServletRequest request) {
        try {
            String jwtToken = request.getHeader("token");
            if (StringUtils.isEmpty(jwtToken)) {
                return false;
            }
            Jwts.parser().setSigningKey(APP_SECRET).parseClaimsJws(jwtToken);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    /**
     * 根據(jù)token獲取會(huì)員id
     *
     * @param request
     * @return
     */
    public static String getMemberIdByJwtToken(HttpServletRequest request) {
        String jwtToken = request.getHeader("token");
        if (StringUtils.isEmpty(jwtToken)) return "";
        Jws<Claims> claimsJws = Jwts.parser().setSigningKey(APP_SECRET).parseClaimsJws(jwtToken);
        Claims claims = claimsJws.getBody();
        return (String) claims.get("id");
    }
}

MD5工具類(lèi)

public final class MD5 {

    /**
     * 傳入字符串,返回經(jīng)過(guò)MD5加密的后的字符串
     *
     * @param strSrc 需要加密的字符串
     * @return 返回加密后的字符串
     */
    public static String encrypt(String strSrc) {
        try {
            //用來(lái)將字節(jié)轉(zhuǎn)換成 16 進(jìn)制表示的字符
            char hexChars[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8',
                    '9', 'a', 'b', 'c', 'd', 'e', 'f'};
            byte[] bytes = strSrc.getBytes();
            //得到實(shí)現(xiàn)指定摘要算法的 MessageDigest對(duì)象
            MessageDigest md = MessageDigest.getInstance("MD5");
            //使用指定的 byte數(shù)組更新摘要
            md.update(bytes);
            //通過(guò)執(zhí)行諸如填充之類(lèi)的最終操作完成哈希計(jì)算。在調(diào)用此方法之后,摘要被重置
            bytes = md.digest();
            int j = bytes.length;
            char[] chars = new char[j * 2];
            int k = 0;
            //從第一個(gè)字節(jié)開(kāi)始,對(duì)每一個(gè)字節(jié),轉(zhuǎn)換成 16 進(jìn)制字符
            for (int i = 0; i < bytes.length; i++) {
                //取第 i 個(gè)字節(jié)
                byte b = bytes[i];
                //取字節(jié)中高 4 位的數(shù)字轉(zhuǎn)換
                chars[k++] = hexChars[b >>> 4 & 0xf];
                //取字節(jié)中低 4 位的數(shù)字轉(zhuǎn)換
                chars[k++] = hexChars[b & 0xf];
            }
            //將轉(zhuǎn)換的結(jié)果轉(zhuǎn)換為字符串返回
            return new String(chars);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            throw new RuntimeException("MD5加密出錯(cuò)!!+" + e);
        }
    }

    public static void main(String[] args) {
        System.out.println(MD5.encrypt("111111"));
    }
}

視頻點(diǎn)播工具類(lèi)

得到視頻點(diǎn)播需要的初始化對(duì)象DefaultAcsClient:

public class InitVodCilent {

    /**
     * 得到視頻點(diǎn)播需要的client
     *
     * @param accessKeyId     id
     * @param accessKeySecret 秘鑰
     * @return 返回DefaultAcsClient對(duì)象
     * @throws ClientException
     */
    public static DefaultAcsClient initVodClient(String accessKeyId, String accessKeySecret) throws ClientException {
        //點(diǎn)播服務(wù)接入?yún)^(qū)域
        String regionId = "cn-shanghai";
        DefaultProfile profile = DefaultProfile.getProfile(regionId, accessKeyId, accessKeySecret);
        DefaultAcsClient client = new DefaultAcsClient(profile);
        return client;
    }
}

公共常量工具類(lèi)

對(duì)于一些微信支付和阿里云OSS等有許多固定地址的,我們可以使用一個(gè)工具類(lèi)定義為常量,方便獲取

這里舉個(gè)栗子

先在配置文件定義:

# 微信開(kāi)放平臺(tái) appid
wx.open.app_id=wxed995adadav4c01bb89b47
# 微信開(kāi)放平臺(tái) appsecret
wx.open.app_secret=a748251723ad5173ddbsfa4083788de60b90e
# 微信開(kāi)放平臺(tái) 重定向url
wx.open.redirect_url=http://localhost:8160/api/ucenter/wx/callback

配置類(lèi):

@Component
public class ConstantWxUtils implements InitializingBean {


    @Value("${wx.open.app_id}")
    private String appId;
    @Value("${wx.open.app_secret}")
    private String appSecret;
    @Value("${wx.open.redirect_url}")
    private String redirectUrl;
    //微信開(kāi)放平臺(tái) appid
    public static String WX_OPEN_APP_ID;
    //微信開(kāi)放平臺(tái) appsecret
    public static String WX_OPEN_APP_SECRET;
    //微信開(kāi)放平臺(tái) 重定向url
    public static String WX_OPEN_REDIRECT_URL;

    //保證了這些值已經(jīng)從配置文件讀取了,在進(jìn)行操作
    @Override
    public void afterPropertiesSet() throws Exception {
        WX_OPEN_APP_ID = appId;
        WX_OPEN_APP_SECRET = appSecret;
        WX_OPEN_REDIRECT_URL = redirectUrl;
    }
}

日期操作工具類(lèi)

這里一共涉及二個(gè)方法:

格式化Date日期,轉(zhuǎn)換為字符串返回

在日期date上增加amount天,返回Data

public class DateUtil {

    private static final String dateFormat = "yyyy-MM-dd";

    /**
     * 格式化日期
     *
     * @param date
     * @return
     */
    public static String formatDate(Date date) {
        SimpleDateFormat sdf = new SimpleDateFormat(dateFormat);
        return sdf.format(date);

    }

    /**
     * 在日期date上增加amount天 
     *
     * @param date   處理的日期,非null
     * @param amount 要加的天數(shù),可能為負(fù)數(shù)
     */
    public static Date addDays(Date date, int amount) {
        Calendar now = Calendar.getInstance();
        now.setTime(date);
        now.set(Calendar.DATE, now.get(Calendar.DATE) + amount);
        return now.getTime();
    }

    public static void main(String[] args) {
        System.out.println(DateUtil.formatDate(new Date()));
        System.out.println(DateUtil.formatDate(DateUtil.addDays(new Date(), -1)));
    }
}

Http客戶(hù)端工具類(lèi)

封裝一個(gè)HttpClientUtils,可以實(shí)現(xiàn):

  1. 發(fā)送一個(gè) Post 請(qǐng)求
  2. 提交form表單
  3. 發(fā)送一個(gè) GET 請(qǐng)求
public class HttpClientUtils {

    public static final int connTimeout=10000;
    public static final int readTimeout=10000;
    public static final String charset="UTF-8";
    private static HttpClient client = null;

    static {
        PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
        cm.setMaxTotal(128);
        cm.setDefaultMaxPerRoute(128);
        client = HttpClients.custom().setConnectionManager(cm).build();
    }

    public static String postParameters(String url, String parameterStr) throws ConnectTimeoutException, SocketTimeoutException, Exception{
        return post(url,parameterStr,"application/x-www-form-urlencoded",charset,connTimeout,readTimeout);
    }

    public static String postParameters(String url, String parameterStr,String charset, Integer connTimeout, Integer readTimeout) throws ConnectTimeoutException, SocketTimeoutException, Exception{
        return post(url,parameterStr,"application/x-www-form-urlencoded",charset,connTimeout,readTimeout);
    }

    public static String postParameters(String url, Map<String, String> params) throws ConnectTimeoutException,
    SocketTimeoutException, Exception {
        return postForm(url, params, null, connTimeout, readTimeout);
    }

    public static String postParameters(String url, Map<String, String> params, Integer connTimeout,Integer readTimeout) throws ConnectTimeoutException,
    SocketTimeoutException, Exception {
        return postForm(url, params, null, connTimeout, readTimeout);
    }

    public static String get(String url) throws Exception {
        return get(url, charset, null, null);
    }

    public static String get(String url, String charset) throws Exception {
        return get(url, charset, connTimeout, readTimeout);
    }

    /**
    * 發(fā)送一個(gè) Post 請(qǐng)求, 使用指定的字符集編碼
    *
    * @param url 請(qǐng)求地址
    * @param body RequestBody
    * @param mimeType 例如 application/xml "application/x-www-form-urlencoded" a=1&b=2&c=3
    * @param charset 編碼
    * @param connTimeout 建立鏈接超時(shí)時(shí)間,毫秒.
    * @param readTimeout 響應(yīng)超時(shí)時(shí)間,毫秒.
    * @return ResponseBody, 使用指定的字符集編碼.
    * @throws ConnectTimeoutException 建立鏈接超時(shí)異常
    * @throws SocketTimeoutException  響應(yīng)超時(shí)
    * @throws Exception
    */
    public static String post(String url, String body, String mimeType,String charset, Integer connTimeout, Integer readTimeout)
        throws ConnectTimeoutException, SocketTimeoutException, Exception {
        HttpClient client = null;
        //創(chuàng)建Http Post請(qǐng)求
        HttpPost post = new HttpPost(url);
        String result = "";
        try {
            if (StringUtils.isNotBlank(body)) {
                HttpEntity entity = new StringEntity(body, ContentType.create(mimeType, charset));
                post.setEntity(entity);
            }
            // 設(shè)置參數(shù)
            Builder customReqConf = RequestConfig.custom();
            if (connTimeout != null) {
                customReqConf.setConnectTimeout(connTimeout);
            }
            if (readTimeout != null) {
                customReqConf.setSocketTimeout(readTimeout);
            }
            post.setConfig(customReqConf.build());

            HttpResponse res;
            if (url.startsWith("https")) {
                // 執(zhí)行 Https 請(qǐng)求
                client = createSSLInsecureClient();
                res = client.execute(post);
            } else {
                // 執(zhí)行 Http 請(qǐng)求
                client = HttpClientUtils.client;
                res = client.execute(post);
            }
            result = IOUtils.toString(res.getEntity().getContent(), charset);
        } finally {
            post.releaseConnection();
            if (url.startsWith("https") && client != null&& client instanceof CloseableHttpClient) {
                ((CloseableHttpClient) client).close();
            }
        }
        return result;
    }


    /**
    * 提交form表單
    *
    * @param url
    * @param params
    * @param connTimeout
    * @param readTimeout
    * @return
    * @throws ConnectTimeoutException
    * @throws SocketTimeoutException
    * @throws Exception
    */
    public static String postForm(String url, Map<String, String> params, Map<String, String> headers, Integer connTimeout,Integer readTimeout) throws ConnectTimeoutException,
    SocketTimeoutException, Exception {

        HttpClient client = null;
        HttpPost post = new HttpPost(url);
        try {
            if (params != null && !params.isEmpty()) {
                List<NameValuePair> formParams = new ArrayList<NameValuePair>();
                Set<Entry<String, String>> entrySet = params.entrySet();
                for (Entry<String, String> entry : entrySet) {
                    formParams.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
                }
                UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formParams, Consts.UTF_8);
                post.setEntity(entity);
            }

            if (headers != null && !headers.isEmpty()) {
                for (Entry<String, String> entry : headers.entrySet()) {
                    post.addHeader(entry.getKey(), entry.getValue());
                }
            }
            // 設(shè)置參數(shù)
            Builder customReqConf = RequestConfig.custom();
            if (connTimeout != null) {
                customReqConf.setConnectTimeout(connTimeout);
            }
            if (readTimeout != null) {
                customReqConf.setSocketTimeout(readTimeout);
            }
            post.setConfig(customReqConf.build());
            HttpResponse res = null;
            if (url.startsWith("https")) {
                // 執(zhí)行 Https 請(qǐng)求.
                client = createSSLInsecureClient();
                res = client.execute(post);
            } else {
                // 執(zhí)行 Http 請(qǐng)求.
                client = HttpClientUtils.client;
                res = client.execute(post);
            }
            return IOUtils.toString(res.getEntity().getContent(), "UTF-8");
        } finally {
            post.releaseConnection();
            if (url.startsWith("https") && client != null
                && client instanceof CloseableHttpClient) {
                ((CloseableHttpClient) client).close();
            }
        }
    }




    /**
    * 發(fā)送一個(gè) GET 請(qǐng)求
    *
    * @param url
    * @param charset
    * @param connTimeout  建立鏈接超時(shí)時(shí)間,毫秒
    * @param readTimeout  響應(yīng)超時(shí)時(shí)間,毫秒
    * @return
    * @throws ConnectTimeoutException   建立鏈接超時(shí)
    * @throws SocketTimeoutException   響應(yīng)超時(shí)
    * @throws Exception
    */
    public static String get(String url, String charset, Integer connTimeout,Integer readTimeout)
        throws ConnectTimeoutException,SocketTimeoutException, Exception {

        HttpClient client = null;

        // 創(chuàng)建http GET請(qǐng)求
        HttpGet get = new HttpGet(url);
        String result = "";
        try {
            // 設(shè)置參數(shù)
            Builder customReqConf = RequestConfig.custom();
            //設(shè)置鏈接超時(shí)時(shí)間,毫秒
            if (connTimeout != null) {
                customReqConf.setConnectTimeout(connTimeout);
            }
            //設(shè)置響應(yīng)超時(shí)時(shí)間,毫秒
            if (readTimeout != null) {
                customReqConf.setSocketTimeout(readTimeout);
            }
            get.setConfig(customReqConf.build());

            HttpResponse res = null;

            if (url.startsWith("https")) {
                // 執(zhí)行 Https 請(qǐng)求
                client = createSSLInsecureClient();
                res = client.execute(get);
            } else {
                // 執(zhí)行 Http 請(qǐng)求
                client = HttpClientUtils.client;
                res = client.execute(get);
            }

            result = IOUtils.toString(res.getEntity().getContent(), charset);
        } finally {
            get.releaseConnection();
            if (url.startsWith("https") && client != null && client instanceof CloseableHttpClient) {
                ((CloseableHttpClient) client).close();
            }
        }
        return result;
    }


    /**
    * 從 response 里獲取 charset
    *
    * @param ressponse
    * @return
    */
    @SuppressWarnings("unused")
    private static String getCharsetFromResponse(HttpResponse ressponse) {
        // Content-Type:text/html; charset=GBK
        if (ressponse.getEntity() != null  && ressponse.getEntity().getContentType() != null && ressponse.getEntity().getContentType().getValue() != null) {
            String contentType = ressponse.getEntity().getContentType().getValue();
            if (contentType.contains("charset=")) {
                return contentType.substring(contentType.indexOf("charset=") + 8);
            }
        }
        return null;
    }



    /**
    * 創(chuàng)建 SSL連接
    * @return
    * @throws GeneralSecurityException
    */
    private static CloseableHttpClient createSSLInsecureClient() throws GeneralSecurityException {
        try {
            SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
                public boolean isTrusted(X509Certificate[] chain,String authType) throws CertificateException {
                    return true;
                }
            }).build();

            SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, new X509HostnameVerifier() {

                @Override
                public boolean verify(String arg0, SSLSession arg1) {
                    return true;
                }

                @Override
                public void verify(String host, SSLSocket ssl)
                    throws IOException {
                }

                @Override
                public void verify(String host, X509Certificate cert)
                    throws SSLException {
                }

                @Override
                public void verify(String host, String[] cns,
                                   String[] subjectAlts) throws SSLException {
                }

            });

            return HttpClients.custom().setSSLSocketFactory(sslsf).build();

        } catch (GeneralSecurityException e) {
            throw e;
        }
    }

    public static void main(String[] args) {
        try {
            String str= post("https://localhost:443/ssl/test.shtml","name=12&page=34","application/x-www-form-urlencoded", "UTF-8", 10000, 10000);
            //String str= get("https://localhost:443/ssl/test.shtml?name=12&page=34","GBK");
            /*Map<String,String> map = new HashMap<String,String>();
            map.put("name", "111");
            map.put("page", "222");
            String str= postForm("https://localhost:443/ssl/test.shtml",map,null, 10000, 10000);*/
            System.out.println(str);
        } catch (ConnectTimeoutException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (SocketTimeoutException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

}

獲取IP工具類(lèi)

根據(jù)request獲取請(qǐng)求的Ip地址:

/**
 * 根據(jù)request獲取請(qǐng)求的Ip地址
 *
 */
@Slf4j
public class IpUtils {

    /**
     * 獲取IP地址
     * 使用Nginx等反向代理軟件, 則不能通過(guò)request.getRemoteAddr()獲取IP地址
     * 如果使用了多級(jí)反向代理的話,X-Forwarded-For的值并不止一個(gè),而是一串IP地址,X-Forwarded-For中第一個(gè)非unknown的有效IP字符串,則為真實(shí)IP地址
     */
    public static String getIpAddr(HttpServletRequest request) {
        String ip = null, unknown = "unknown", seperator = ",";
        int maxLength = 15;
        try {
            ip = request.getHeader("x-forwarded-for");
            if (StringUtils.isEmpty(ip) || unknown.equalsIgnoreCase(ip)) {
                ip = request.getHeader("Proxy-Client-IP");
            }
            if (StringUtils.isEmpty(ip) || ip.length() == 0 || unknown.equalsIgnoreCase(ip)) {
                ip = request.getHeader("WL-Proxy-Client-IP");
            }
            if (StringUtils.isEmpty(ip) || unknown.equalsIgnoreCase(ip)) {
                ip = request.getHeader("HTTP_CLIENT_IP");
            }
            if (StringUtils.isEmpty(ip) || unknown.equalsIgnoreCase(ip)) {
                ip = request.getHeader("HTTP_X_FORWARDED_FOR");
            }
            if (StringUtils.isEmpty(ip) || unknown.equalsIgnoreCase(ip)) {
                ip = request.getRemoteAddr();
            }
        } catch (Exception e) {
            log.error("IpUtils ERROR ", e);
        }

        // 使用代理,則獲取第一個(gè)IP地址
        if (StringUtils.isEmpty(ip) && ip.length() > maxLength) {
            int idx = ip.indexOf(seperator);
            if (idx > 0) {
                ip = ip.substring(0, idx);
            }
        }

        return ip;
    }

    /**
     * 獲取ip地址
     *
     * @return
     */
    public static String getIpAddr() {
        HttpServletRequest request = HttpContextUtils.getHttpServletRequest();
        return getIpAddr(request);
    }
}

獲取請(qǐng)求工具類(lèi):

/**
 * 獲取請(qǐng)求工具類(lèi)
 */
public class HttpContextUtils {
    public static HttpServletRequest getHttpServletRequest(){
        return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
    }
} 

以上就是Java項(xiàng)目常見(jiàn)工具類(lèi)詳解的詳細(xì)內(nèi)容,更多關(guān)于Java工具類(lèi)的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!

相關(guān)文章

最新評(píng)論