Java项目常见工具类详解
更新时间:2021年12月24日 15:14:32 作者:LL.LEBRON
这篇文章主要为大家总结了平时在Java项目中使用的工具类:JWT工具类、MD5工具类、视频点播工具类、公共常量工具类、日期操作工具类、Http客户端工具类和获取IP工具类。需要的可以参考一下
JWT工具类
这里一共涉及四个方法:
传入用户信息获得token
传入token字符串判断token是否存在与有效
传入HttpServletRequest,通过获取Header中的token判断是否存在与有效
根据token获取用户id
public class JwtUtils { //token过期时间 public static final long EXPIRE = 1000 * 60 * 60 * 24; //秘钥 public static final String APP_SECRET = "ukc8BDbRigUDaY6pZFfWus2jZWLPHO"; /** * 获得token * * @param id 用户id * @param nickname 用户昵称 * @return */ public static String getJwtToken(String id, String nickname) { String JwtToken = Jwts.builder() //设置jwt头信息 .setHeaderParam("typ", "JWT") .setHeaderParam("alg", "HS256") //设置分类 .setSubject("guli-user") //设置签发时间 .setIssuedAt(new Date()) //设置过期时间=当前时间+过多久过期的时间 .setExpiration(new Date(System.currentTimeMillis() + EXPIRE)) //设置token主体部分,存储用户信息 .claim("id", id) .claim("nickname", nickname) //设置签发算法+秘钥 .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 { //验证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; } /** * 根据token获取会员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工具类
public final class MD5 { /** * 传入字符串,返回经过MD5加密的后的字符串 * * @param strSrc 需要加密的字符串 * @return 返回加密后的字符串 */ public static String encrypt(String strSrc) { try { //用来将字节转换成 16 进制表示的字符 char hexChars[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'}; byte[] bytes = strSrc.getBytes(); //得到实现指定摘要算法的 MessageDigest对象 MessageDigest md = MessageDigest.getInstance("MD5"); //使用指定的 byte数组更新摘要 md.update(bytes); //通过执行诸如填充之类的最终操作完成哈希计算。在调用此方法之后,摘要被重置 bytes = md.digest(); int j = bytes.length; char[] chars = new char[j * 2]; int k = 0; //从第一个字节开始,对每一个字节,转换成 16 进制字符 for (int i = 0; i < bytes.length; i++) { //取第 i 个字节 byte b = bytes[i]; //取字节中高 4 位的数字转换 chars[k++] = hexChars[b >>> 4 & 0xf]; //取字节中低 4 位的数字转换 chars[k++] = hexChars[b & 0xf]; } //将转换的结果转换为字符串返回 return new String(chars); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); throw new RuntimeException("MD5加密出错!!+" + e); } } public static void main(String[] args) { System.out.println(MD5.encrypt("111111")); } }
视频点播工具类
得到视频点播需要的初始化对象DefaultAcsClient:
public class InitVodCilent { /** * 得到视频点播需要的client * * @param accessKeyId id * @param accessKeySecret 秘钥 * @return 返回DefaultAcsClient对象 * @throws ClientException */ public static DefaultAcsClient initVodClient(String accessKeyId, String accessKeySecret) throws ClientException { //点播服务接入区域 String regionId = "cn-shanghai"; DefaultProfile profile = DefaultProfile.getProfile(regionId, accessKeyId, accessKeySecret); DefaultAcsClient client = new DefaultAcsClient(profile); return client; } }
公共常量工具类
对于一些微信支付和阿里云OSS等有许多固定地址的,我们可以使用一个工具类定义为常量,方便获取
这里举个栗子
先在配置文件定义:
# 微信开放平台 appid wx.open.app_id=wxed995adadav4c01bb89b47 # 微信开放平台 appsecret wx.open.app_secret=a748251723ad5173ddbsfa4083788de60b90e # 微信开放平台 重定向url wx.open.redirect_url=http://localhost:8160/api/ucenter/wx/callback
配置类:
@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; //微信开放平台 appid public static String WX_OPEN_APP_ID; //微信开放平台 appsecret public static String WX_OPEN_APP_SECRET; //微信开放平台 重定向url public static String WX_OPEN_REDIRECT_URL; //保证了这些值已经从配置文件读取了,在进行操作 @Override public void afterPropertiesSet() throws Exception { WX_OPEN_APP_ID = appId; WX_OPEN_APP_SECRET = appSecret; WX_OPEN_REDIRECT_URL = redirectUrl; } }
日期操作工具类
这里一共涉及二个方法:
格式化Date日期,转换为字符串返回
在日期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 要加的天数,可能为负数 */ 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客户端工具类
封装一个HttpClientUtils,可以实现:
- 发送一个 Post 请求
- 提交form表单
- 发送一个 GET 请求
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); } /** * 发送一个 Post 请求, 使用指定的字符集编码 * * @param url 请求地址 * @param body RequestBody * @param mimeType 例如 application/xml "application/x-www-form-urlencoded" a=1&b=2&c=3 * @param charset 编码 * @param connTimeout 建立链接超时时间,毫秒. * @param readTimeout 响应超时时间,毫秒. * @return ResponseBody, 使用指定的字符集编码. * @throws ConnectTimeoutException 建立链接超时异常 * @throws SocketTimeoutException 响应超时 * @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; //创建Http Post请求 HttpPost post = new HttpPost(url); String result = ""; try { if (StringUtils.isNotBlank(body)) { HttpEntity entity = new StringEntity(body, ContentType.create(mimeType, charset)); post.setEntity(entity); } // 设置参数 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")) { // 执行 Https 请求 client = createSSLInsecureClient(); res = client.execute(post); } else { // 执行 Http 请求 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()); } } // 设置参数 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")) { // 执行 Https 请求. client = createSSLInsecureClient(); res = client.execute(post); } else { // 执行 Http 请求. 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(); } } } /** * 发送一个 GET 请求 * * @param url * @param charset * @param connTimeout 建立链接超时时间,毫秒 * @param readTimeout 响应超时时间,毫秒 * @return * @throws ConnectTimeoutException 建立链接超时 * @throws SocketTimeoutException 响应超时 * @throws Exception */ public static String get(String url, String charset, Integer connTimeout,Integer readTimeout) throws ConnectTimeoutException,SocketTimeoutException, Exception { HttpClient client = null; // 创建http GET请求 HttpGet get = new HttpGet(url); String result = ""; try { // 设置参数 Builder customReqConf = RequestConfig.custom(); //设置链接超时时间,毫秒 if (connTimeout != null) { customReqConf.setConnectTimeout(connTimeout); } //设置响应超时时间,毫秒 if (readTimeout != null) { customReqConf.setSocketTimeout(readTimeout); } get.setConfig(customReqConf.build()); HttpResponse res = null; if (url.startsWith("https")) { // 执行 Https 请求 client = createSSLInsecureClient(); res = client.execute(get); } else { // 执行 Http 请求 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; } /** * 创建 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工具类
根据request获取请求的Ip地址:
/** * 根据request获取请求的Ip地址 * */ @Slf4j public class IpUtils { /** * 获取IP地址 * 使用Nginx等反向代理软件, 则不能通过request.getRemoteAddr()获取IP地址 * 如果使用了多级反向代理的话,X-Forwarded-For的值并不止一个,而是一串IP地址,X-Forwarded-For中第一个非unknown的有效IP字符串,则为真实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); } // 使用代理,则获取第一个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); } }
获取请求工具类:
/**
* 获取请求工具类
*/
public class HttpContextUtils {
public static HttpServletRequest getHttpServletRequest(){
return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
}
}
以上就是Java项目常见工具类详解的详细内容,更多关于Java工具类的资料请关注脚本之家其它相关文章!
最新评论