JAVA Utils 實用工具類

目錄

1.Email 發送郵件工具

2.隨機數字 驗證碼工具

3.cookieUtsil 操作cookie的基本工具

4.HttpclientUtil  發送Get Post請求

 5.MD5Util 

6.HTTPClient

1.Email 發送郵件工具

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Properties;

/**
 * 發郵件工具類
 */
public final class MailUtils {
    private static final String USER = "[email protected]"; // 發件人稱號,同郵箱地址
    private static final String PASSWORD = "xxxxxxxxx"; // 如果是qq郵箱可以使戶端授權碼,或者登錄密碼

    /**
     * @param to 收件人郵箱
     * @param text 郵件正文
     * @param title 標題
     */
    /* 發送驗證信息的郵件 */
    public static boolean sendMail(String to, String text, String title){
        try {
            final Properties props = new Properties();
            props.put("mail.smtp.auth", "true");
            props.put("mail.smtp.host", "smtp.qq.com");

            // 發件人的賬號
            props.put("mail.user", USER);
            //發件人的密碼
            props.put("mail.password", PASSWORD);

            // 構建授權信息,用於進行SMTP進行身份驗證
            Authenticator authenticator = new Authenticator() {
                @Override
                protected PasswordAuthentication getPasswordAuthentication() {
                    // 用戶名、密碼
                    String userName = props.getProperty("mail.user");
                    String password = props.getProperty("mail.password");
                    return new PasswordAuthentication(userName, password);
                }
            };
            // 使用環境屬性和授權信息,創建郵件會話
            Session mailSession = Session.getInstance(props, authenticator);
            // 創建郵件消息
            MimeMessage message = new MimeMessage(mailSession);
            // 設置發件人
            String username = props.getProperty("mail.user");
            InternetAddress form = new InternetAddress(username);
            message.setFrom(form);

            // 設置收件人
            InternetAddress toAddress = new InternetAddress(to);
            message.setRecipient(Message.RecipientType.TO, toAddress);

            // 設置郵件標題
            message.setSubject(title);

            // 設置郵件的內容體
            message.setContent(text, "text/html;charset=UTF-8");
            // 發送郵件
            Transport.send(message);
            return true;
        }catch (Exception e){
            System.out.println("出錯了");
        }
        return false;
    }

//    public static void main(String[] args) throws Exception { // 做測試用
//        MailUtils.sendMail("[email protected]","你好,這是一封測試郵件,無需回覆。","測試郵件");
//        System.out.println("發送成功");
//    }

}

2.隨機數字 驗證碼工具

/**
 * 驗證碼
 */
@WebServlet("/checkCode")
public class CheckCodeServlet extends HttpServlet {
	public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {
		
		//服務器通知瀏覽器不要緩存
		response.setHeader("pragma","no-cache");
		response.setHeader("cache-control","no-cache");
		response.setHeader("expires","0");
		
		//在內存中創建一個長80,寬30的圖片,默認黑色背景
		//參數一:長
		//參數二:寬
		//參數三:顏色
		int width = 80;
		int height = 30;
		BufferedImage image = new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);
		
		//獲取畫筆
		Graphics g = image.getGraphics();
		//設置畫筆顏色爲灰色
		g.setColor(Color.GRAY);
		//填充圖片
		g.fillRect(0,0, width,height);
		
		//產生4個隨機驗證碼,12Ey
		String checkCode = getCheckCode();
		//將驗證碼放入HttpSession中
		request.getSession().setAttribute("CHECKCODE_SERVER",checkCode);
		
		//設置畫筆顏色爲黃色
		g.setColor(Color.YELLOW);
		//設置字體的小大
		g.setFont(new Font("黑體",Font.BOLD,24));
		//向圖片上寫入驗證碼
		g.drawString(checkCode,15,25);
		
		//將內存中的圖片輸出到瀏覽器
		//參數一:圖片對象
		//參數二:圖片的格式,如PNG,JPG,GIF
		//參數三:圖片輸出到哪裏去
		ImageIO.write(image,"PNG",response.getOutputStream());
	}

	/**
	 * 產生4位隨機字符串 
	 */
	private String getCheckCode() {
		String base = "0123456789ABCDEFGabcdefg";
		int size = base.length();
		Random r = new Random();
		StringBuffer sb = new StringBuffer();
		for(int i=1;i<=4;i++){
			//產生0到size-1的隨機值
			int index = r.nextInt(size);
			//在base字符串中獲取下標爲index的字符
			char c = base.charAt(index);
			//將c放入到StringBuffer中去
			sb.append(c);
		}
		return sb.toString();
	}

3.cookieUtsil 操作cookie的基本工具

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
/**
 * @param
 * @return
 */
public class CookieUtil {
    /***
     * 獲得cookie中的值,默認爲主ip:www.book.com
     * @param request
     * @param cookieName
     * @param isDecoder
     * @return
     */
    public static String getCookieValue(HttpServletRequest request, String cookieName, boolean isDecoder) {
        Cookie[] cookies = request.getCookies();
        if (cookies == null || cookieName == null){
            return null;
        }
        String retValue = null;
        try {
            for (int i = 0; i < cookies.length; i++) {
                if (cookies[i].getName().equals(cookieName)) {
                    if (isDecoder) {//如果涉及中文
                        retValue = URLDecoder.decode(cookies[i].getValue(), "UTF-8");
                    } else {
                        retValue = cookies[i].getValue();
                    }
                    break;
                }
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return retValue;
    }
    /***
     * 設置cookie的值
     * @param request
     * @param response
     * @param cookieName
     * @param cookieValue
     * @param cookieMaxage
     * @param isEncode
     */
    public static   void setCookie(HttpServletRequest request, HttpServletResponse response, String cookieName, String cookieValue, int cookieMaxage, boolean isEncode) {
        try {
            if (cookieValue == null) {
                cookieValue = "";
            } else if (isEncode) {
                cookieValue = URLEncoder.encode(cookieValue, "utf-8");
            }
            Cookie cookie = new Cookie(cookieName, cookieValue);
            if (cookieMaxage >= 0)
                cookie.setMaxAge(cookieMaxage);
            if (null != request)// 設置域名的cookie
                cookie.setDomain(getDomainName(request));
            // 在域名的根路徑下保存
            cookie.setPath("/");
            response.addCookie(cookie);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    /***
     * 獲得cookie的主域名,本系統爲book.com,保存時使用
     * @param request
     * @return
     */
    private static final String getDomainName(HttpServletRequest request) {
        String domainName = null;
        String serverName = request.getRequestURL().toString();
        if (serverName == null || serverName.equals("")) {
            domainName = "";
        } else {
            serverName = serverName.toLowerCase();
            //去掉前面http://
            serverName = serverName.substring(7);
            //的到第一個/的位置www.cart.com/123/3
            final int end = serverName.indexOf("/");
            //去掉後面沒用的url路徑  www.cart.com
            serverName = serverName.substring(0, end);
            //得到[www,cart,com]
            final String[] domains = serverName.split("\\.");
            int len = domains.length;
            if (len > 3) {
                // www.xxx.com.cn
                domainName = domains[len - 3] + "." + domains[len - 2] + "." + domains[len - 1];
            } else if (len <= 3 && len > 1) {
                // xxx.com or xxx.cn
                              //取一級域名              //的到.com 或者.cn
                domainName = domains[len - 2] + "." + domains[len - 1];
            } else {
                domainName = serverName;
            }
        }
        if (domainName != null && domainName.indexOf(":") > 0) {
            String[] ary = domainName.split("\\:");
            domainName = ary[0];
        }
        System.out.println("domainName = " + domainName);
        return domainName;
    }
    /***
     * 將cookie中的內容按照key刪除
     * @param request
     * @param response
     * @param cookieName
     */
    public static void deleteCookie(HttpServletRequest request, HttpServletResponse response, String cookieName) {
        setCookie(request, response, cookieName, null, 0, false);
    }
}

4.HttpclientUtil  發送Get Post請求

public class HttpclientUtil {

    public static String doGet(String url)   {
        // 創建Httpclient對象
        CloseableHttpClient httpclient = HttpClients.createDefault();
        // 創建http GET請求
        HttpGet httpGet = new HttpGet(url);
        CloseableHttpResponse response = null;
        try {
            // 執行請求
            response = httpclient.execute(httpGet);
            // 判斷返回狀態是否爲200
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                HttpEntity entity = response.getEntity();
                String result = EntityUtils.toString(entity, "UTF-8");
                EntityUtils.consume(entity);
                httpclient.close();
                return result;
            }
            httpclient.close();
        }catch (IOException e){
            e.printStackTrace();
            return null;
        }
        return  null;
    }



    public static String doPost(String url, Map<String,String> paramMap)   {
       // 創建Httpclient對象
        CloseableHttpClient httpclient = HttpClients.createDefault();
        // 創建http Post請求
        HttpPost httpPost = new HttpPost(url);
        CloseableHttpResponse response = null;
        try {
            List<BasicNameValuePair> list=new ArrayList<>();
            for (Map.Entry<String, String> entry : paramMap.entrySet()) {
                list.add(new BasicNameValuePair(entry.getKey(),entry.getValue())) ;
            }
            HttpEntity httpEntity=new UrlEncodedFormEntity(list,"utf-8");

            httpPost.setEntity(httpEntity);
            // 執行請求
            response = httpclient.execute(httpPost);

            // 判斷返回狀態是否爲200
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                HttpEntity entity = response.getEntity();
                String result = EntityUtils.toString(entity, "UTF-8");
                EntityUtils.consume(entity);
                httpclient.close();
                return result;
            }
            httpclient.close();
        }catch (IOException e){
            e.printStackTrace();
            return null;
        }

        return  null;
    }
}

 5.MD5Util 

public class MD5Util {

    /**
     * The M d5.
     */
    static MessageDigest MD5 = null;

    /**
     * The Constant HEX_DIGITS.
     */
    private static final char HEX_DIGITS[] = {'0', '1', '2', '3', '4', '5',
            '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};

    static {
        try {
            MD5 = MessageDigest.getInstance("MD5");
        } catch (NoSuchAlgorithmException ne) {
            ne.printStackTrace();
        }
    }

    /**
     * 獲取文件md5值.
     * @param file the file
     * @return md5串
     * @throws IOException
     */
    public static String getFileMD5String(File file) throws IOException {
        FileInputStream fileInputStream = null;
        try {
            fileInputStream = new FileInputStream(file);
            byte[] buffer = new byte[8192];
            int length;
            while ((length = fileInputStream.read(buffer)) != -1) {
                MD5.update(buffer, 0, length);
            }

            return new String(encodeHex(MD5.digest()));
        } catch (FileNotFoundException e) {
            throw e;
        } catch (IOException e) {
            throw e;
        } finally {
            try {
                if (fileInputStream != null)
                    fileInputStream.close();
            } catch (IOException e) {
                throw e;
            }
        }
    }

    /**
     * 獲取文件md5值.
     *
     * @param data the byte[] data
     * @return md5串
     * @throws IOException
     */
    public static String getFileMD5String(byte[] data) throws IOException {
        MD5.update(data);
        return new String(encodeHex(MD5.digest()));
    }

    /**
     * Encode hex.
     *
     * @param bytes the bytes
     * @return the string
     */
    public static String encodeHex(byte bytes[]) {
        return bytesToHex(bytes, 0, bytes.length);

    }

    /**
     * Bytes to hex.
     *
     * @param bytes the bytes
     * @param start the start
     * @param end   the end
     * @return the string
     */
    public static String bytesToHex(byte bytes[], int start, int end) {
        StringBuilder sb = new StringBuilder();
        for (int i = start; i < start + end; i++) {
            sb.append(byteToHex(bytes[i]));
        }
        return sb.toString();

    }

    /**
     * Byte to hex.
     *
     * @param bt the bt
     * @return the string
     */
    public static String byteToHex(byte bt) {
        return HEX_DIGITS[(bt & 0xf0) >> 4] + "" + HEX_DIGITS[bt & 0xf];

    }

    /**
     * 獲取md5值.
     *
     * @param str the string
     * @return md5串
     * @throws IOException
     */
    public static String getStringMD5(String str) {
        StringBuilder sb = new StringBuilder();
        try {
            byte[] data = str.getBytes("utf-8");
            MessageDigest MD5 = MessageDigest.getInstance("MD5");
            MD5.update(data);
            data = MD5.digest();
            for (int i = 0; i < data.length; i++) {
                sb.append(HEX_DIGITS[(data[i] & 0xf0) >> 4] + "" + HEX_DIGITS[data[i] & 0xf]);
            }
        } catch (Exception e) {
        }
        return sb.toString();
    }

    /**
     * The main method.
     *
     * @param args the arguments
     */
    public static void main(String[] args) {

        long beginTime = System.currentTimeMillis();
        File fileZIP = new File("D:\\BaiduNetdiskDownload\\test1.avi");

        String md5 = "";
        try {
            md5 = getFileMD5String(fileZIP);
        } catch (IOException e) {
            e.printStackTrace();
        }
        long endTime = System.currentTimeMillis();
        System.out.println("MD5:" + md5 + "\n time:" + ((endTime - beginTime)) + "ms");

        System.out.println(getStringMD5("111111"));
    }
}

6.HTTPClient

public class HttpclientUtil {

    public static String doGet(String url) {
        // 創建Httpclient對象
        CloseableHttpClient httpclient = HttpClients.createDefault();
        // 創建http GET請求
        HttpGet httpGet = new HttpGet(url);
        CloseableHttpResponse response = null;
        try {
            // 執行請求
            response = httpclient.execute(httpGet);
            // 判斷返回狀態是否爲200
            HttpEntity entity = response.getEntity();
            String result = EntityUtils.toString(entity, "UTF-8");
            EntityUtils.consume(entity);  //釋放資源
            httpclient.close();
            return result;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        } finally {
            try {
                httpclient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }


    public static String doPost(String url, Map<String, String> paramMap) {
        // 創建Httpclient對象
        CloseableHttpClient httpclient = HttpClients.createDefault();
        // 創建http Post請求
        HttpPost httpPost = new HttpPost(url);
        CloseableHttpResponse response = null;
        try {
            if (paramMap != null) {
                List<BasicNameValuePair> list = new ArrayList<>();
                for (Map.Entry<String, String> entry : paramMap.entrySet()) {
                    list.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
                }
                HttpEntity httpEntity = new UrlEncodedFormEntity(list, "utf-8");
                httpPost.setEntity(httpEntity);
            }
            // 執行請求
            response = httpclient.execute(httpPost);

            // 判斷返回狀態是否爲200

            HttpEntity entity = response.getEntity();
            String result = EntityUtils.toString(entity, "UTF-8");
            EntityUtils.consume(entity);  //釋放資源
            httpclient.close();
            return result;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        } finally {
            try {
                httpclient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

 

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