日期操作类 + http、https 请求工具类 + 开发环境 忽略 SSL 验证工具类 + 二维码工具类

news/2024/9/23 14:24:09/

日期操作类

package com.pay.common.util;import java.text.SimpleDateFormat;
import java.util.Date;
/*** 日期操作类* 创建者 科帮网* 创建时间	2017年7月31日*/
public class DateUtils {private final static SimpleDateFormat sdfYear = new SimpleDateFormat("yyyy");private final static SimpleDateFormat sdfDay = new SimpleDateFormat("yyyy-MM-dd");private final static SimpleDateFormat sdfDays = new SimpleDateFormat("yyyyMMdd");private final static SimpleDateFormat sdfTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");/*** 获取YYYY-MM-DD hh:mm:ss格式** @return*/public static String getTime() {return sdfTime.format(new Date());}public static String getTimestamp() {return String.valueOf(System.currentTimeMillis() / 1000);}
}

http、https 请求工具类

package com.pay.common.util;import org.springframework.util.StringUtils;import javax.net.ssl.*;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.Map;
import java.util.Map.Entry;/*** http、https 请求工具类** @author jiaxiaoxian*/
public class HttpUtils {private static final String DEFAULT_CHARSET = "UTF-8";private static final String _GET = "GET"; // GETprivate static final String _POST = "POST";// POSTpublic static final int DEF_CONN_TIMEOUT = 30000;public static final int DEF_READ_TIMEOUT = 30000;/*** 初始化http请求参数** @param url* @param method* @param headers* @return* @throws Exception*/private static HttpURLConnection initHttp(String url, String method,Map<String, String> headers) throws Exception {URL _url = new URL(url);HttpURLConnection http = (HttpURLConnection) _url.openConnection();// 连接超时http.setConnectTimeout(DEF_CONN_TIMEOUT);// 读取超时 --服务器响应比较慢,增大时间http.setReadTimeout(DEF_READ_TIMEOUT);http.setUseCaches(false);http.setRequestMethod(method);http.setRequestProperty("Content-Type","application/x-www-form-urlencoded");http.setRequestProperty("User-Agent","Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.146 Safari/537.36");if (null != headers && !headers.isEmpty()) {for (Entry<String, String> entry : headers.entrySet()) {http.setRequestProperty(entry.getKey(), entry.getValue());}}http.setDoOutput(true);http.setDoInput(true);http.connect();return http;}/*** 初始化http请求参数** @param url* @param method* @return* @throws Exception*/private static HttpsURLConnection initHttps(String url, String method,Map<String, String> headers) throws Exception {TrustManager[] tm = {new MyX509TrustManager()};System.setProperty("https.protocols", "TLSv1");SSLContext sslContext = SSLContext.getInstance("TLS");sslContext.init(null, tm, new java.security.SecureRandom());// 从上述SSLContext对象中得到SSLSocketFactory对象SSLSocketFactory ssf = sslContext.getSocketFactory();URL _url = new URL(url);HttpsURLConnection http = (HttpsURLConnection) _url.openConnection();// 设置域名校验http.setHostnameVerifier(new HttpUtils().new TrustAnyHostnameVerifier());// 连接超时http.setConnectTimeout(DEF_CONN_TIMEOUT);// 读取超时 --服务器响应比较慢,增大时间http.setReadTimeout(DEF_READ_TIMEOUT);http.setUseCaches(false);http.setRequestMethod(method);http.setRequestProperty("Content-Type","application/x-www-form-urlencoded");http.setRequestProperty("User-Agent","Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.146 Safari/537.36");if (null != headers && !headers.isEmpty()) {for (Entry<String, String> entry : headers.entrySet()) {http.setRequestProperty(entry.getKey(), entry.getValue());}}http.setSSLSocketFactory(ssf);http.setDoOutput(true);http.setDoInput(true);http.connect();return http;}/*** @return 返回类型:* @throws Exception* @description 功能描述: get 请求*/public static String get(String url, Map<String, String> params,Map<String, String> headers) throws Exception {HttpURLConnection http = null;if (isHttps(url)) {http = initHttps(initParams(url, params), _GET, headers);} else {http = initHttp(initParams(url, params), _GET, headers);}InputStream in = http.getInputStream();BufferedReader read = new BufferedReader(new InputStreamReader(in,DEFAULT_CHARSET));String valueString = null;StringBuffer bufferRes = new StringBuffer();// 优化,不能光使用!=null做判断。有为""的情况,防止多次空循环while (!StringUtils.isEmpty(valueString = read.readLine())) {bufferRes.append(valueString);}in.close();if (http != null) {http.disconnect();// 关闭连接}return bufferRes.toString();}public static String get(String url) throws Exception {return get(url, null);}public static String get(String url, Map<String, String> params)throws Exception {return get(url, params, null);}public static String post(String url, String params) throws Exception {HttpURLConnection http = null;if (isHttps(url)) {http = initHttps(url, _POST, null);} else {http = initHttp(url, _POST, null);}OutputStream out = http.getOutputStream();out.write(params.getBytes(DEFAULT_CHARSET));out.flush();out.close();InputStream in = http.getInputStream();BufferedReader read = new BufferedReader(new InputStreamReader(in,DEFAULT_CHARSET));String valueString = null;StringBuffer bufferRes = new StringBuffer();while ((valueString = read.readLine()) != null) {bufferRes.append(valueString);}in.close();if (http != null) {http.disconnect();// 关闭连接}return bufferRes.toString();}public static String post(String url, String params, Map<String, String> headers) throws Exception {HttpURLConnection http = null;if (isHttps(url)) {http = initHttps(url, _POST, headers);} else {http = initHttp(url, _POST, headers);}OutputStream out = http.getOutputStream();out.write(params.getBytes(DEFAULT_CHARSET));out.flush();out.close();InputStream in = http.getInputStream();BufferedReader read = new BufferedReader(new InputStreamReader(in,DEFAULT_CHARSET));String valueString = null;StringBuffer bufferRes = new StringBuffer();while ((valueString = read.readLine()) != null) {bufferRes.append(valueString);}in.close();if (http != null) {http.disconnect();// 关闭连接}return bufferRes.toString();}/*** 功能描述: 构造请求参数** @return 返回类型:* @throws Exception*/public static String initParams(String url, Map<String, String> params)throws Exception {if (null == params || params.isEmpty()) {return url;}StringBuilder sb = new StringBuilder(url);if (url.indexOf("?") == -1) {sb.append("?");}sb.append(map2Url(params));return sb.toString();}/*** map构造url** @return 返回类型:* @throws Exception*/public static String map2Url(Map<String, String> paramToMap)throws Exception {if (null == paramToMap || paramToMap.isEmpty()) {return null;}StringBuffer url = new StringBuffer();boolean isfist = true;for (Entry<String, String> entry : paramToMap.entrySet()) {if (isfist) {isfist = false;} else {url.append("&");}url.append(entry.getKey()).append("=");String value = entry.getValue();if (!StringUtils.isEmpty(value)) {url.append(URLEncoder.encode(value, DEFAULT_CHARSET));}}return url.toString();}/*** 检测是否https** @param url*/private static boolean isHttps(String url) {return url.startsWith("https");}/*** https 域名校验* @return*/public class TrustAnyHostnameVerifier implements HostnameVerifier {@Overridepublic boolean verify(String hostname, SSLSession session) {return true;// 直接返回true}}private static class MyX509TrustManager implements X509TrustManager {@Overridepublic X509Certificate[] getAcceptedIssuers() {return null;}@Overridepublic void checkServerTrusted(X509Certificate[] chain, String authType)throws CertificateException {}@Overridepublic void checkClientTrusted(X509Certificate[] chain, String authType)throws CertificateException {}};public static void main(String[] args) {String str = "";try {str = get("https://www.baidu.com");} catch (Exception e) {// TODO Auto-generated catch blocke.printStackTrace();}System.out.println(str);}}

开发环境 忽略 SSL 验证工具类

package com.pay.common.util;import javax.net.ssl.*;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;/*** 开发环境 忽略 SSL 验证* 爪哇笔记:https://blog.52itstyle.vip* @author 小柒2012*/
public class SslUtils {private static void trustAllHttpsCertificates() throws Exception {TrustManager[] trustAllCerts = new TrustManager[1];TrustManager tm = new miTM();trustAllCerts[0] = tm;SSLContext sc = SSLContext.getInstance("SSL");sc.init(null, trustAllCerts, null);HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());}static class miTM implements TrustManager,X509TrustManager {@Overridepublic X509Certificate[] getAcceptedIssuers() {return null;}public boolean isServerTrusted(X509Certificate[] certs) {return true;}public boolean isClientTrusted(X509Certificate[] certs) {return true;}@Overridepublic void checkServerTrusted(X509Certificate[] certs, String authType)throws CertificateException {return;}@Overridepublic void checkClientTrusted(X509Certificate[] certs, String authType)throws CertificateException {return;}}/*** 忽略HTTPS请求的SSL证书,必须在openConnection之前调用* @throws Exception*/public static void ignoreSsl() throws Exception{HostnameVerifier hv = (urlHostName, session) -> {System.out.println("Warning: URL Host: " + urlHostName + " vs. " + session.getPeerHost());return true;};trustAllHttpsCertificates();HttpsURLConnection.setDefaultHostnameVerifier(hv);}}

二维码

package com.pay.common.util;import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;import java.io.File;
import java.io.IOException;
import java.util.HashMap;/*** 二维码* 爪哇笔记:https://blog.52itstyle.vip* @author 小柒2012*/
public class ZxingUtils {static final String FORMAT = "png";static final int height = 256;/*** 生成二维码* @param qrCode* @param imgPath*/public static void createQRCodeImage(String qrCode,String imgPath){HashMap hashMap = new HashMap();hashMap.put(EncodeHintType.CHARACTER_SET, "UTF-8");hashMap.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M);hashMap.put(EncodeHintType.MARGIN, 2);try {BitMatrix bitMatrix = new MultiFormatWriter().encode(qrCode, BarcodeFormat.QR_CODE, height, height, hashMap);MatrixToImageWriter.writeToPath(bitMatrix, FORMAT, new File(imgPath).toPath());} catch (WriterException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}}
}

http://www.ppmy.cn/news/1440792.html

相关文章

重学java 24.面向对象 多态

下雨了&#xff0c;跑不跑衣服都会被淋湿&#xff0c;还不如慢慢地走&#xff0c;结局已定 —— 24.4.25 多态 1.面向对象三大特性&#xff1a;封装 继承 多态 2.怎么学&#xff1a; a、不要从字面意思上理解多态这两个字&#xff0c;要从使用形式上掌握 b、要知…

书生·浦语大模型开源体系(四)笔记

&#x1f497;&#x1f497;&#x1f497;欢迎来到我的博客&#xff0c;你将找到有关如何使用技术解决问题的文章&#xff0c;也会找到某个技术的学习路线。无论你是何种职业&#xff0c;我都希望我的博客对你有所帮助。最后不要忘记订阅我的博客以获取最新文章&#xff0c;也欢…

Typecho主题 - 一款视频ZeVideo开源主题

ZeVideo最为一款免费开源的视频主题&#xff0c;本次更新我们重构了代码结构。 全站pjax无刷新加载&#xff0c;支持根据系统进入深色模式&#xff0c;或手动切换&#xff0c;支持记录播放历史功能&#xff0c;首页布局支持自定义&#xff0c;主题设置支持修改logo&#xff0c…

debian gnome-desktop GUI(图形用户界面)系统

目录 &#x1f31e;更新 &#x1f3a8;安装 &#x1f34e;分配 &#x1f6cb;️重启 &#x1f511;通过VNC连接 debian gnome-desktop &#x1f31e;更新 sudo apt update sudo apt -y upgrade &#x1f3a8;安装 sudo apt -y install task-gnome-desktop 这个过程比…

《深入浅出.NET框架设计与实现》笔记6.3——ASP.NET Core应用程序多种运行模式之三——桌面应用程序

ASP.NET Core应用程序可以在多种运行模式下运行&#xff0c;包括自宿主&#xff08;Self-Hosting&#xff09;、IIS服务承载、桌面应用程序、服务承载。 因此选择和时的模式很重要。 桌面应用程序 ASP.NET Core也可以用于构建跨平台的桌面应用程序&#xff0c;利用跨平台界面…

村集体建设用地,开发乡村旅游项目,土地如何审批?

以村集体建设用地,开发乡村旅游项目,土地如何审批? 乡村&#xff0c;作为承载乡村旅游产业的载体&#xff0c;在乡村振兴中扮演着非常重要的角色。 项目的落地&#xff0c;可靠的土地是必要的前提。集体建设用地如何审批&#xff1f;农转非又需要什么样的流程&#xff0c;具体…

自动化软件测试策略

作为一名软件开发人员&#xff0c;我在不同的公司工作过&#xff0c;具有不同的软件测试流程。在大多数情况下&#xff0c;没有特定/记录的测试方法......因此该过程的内容/方式取决于各个开发人员。与大多数情况一样&#xff0c;当没有强制执行或至少记录在案的政策时&#xf…

递归、搜索与回溯算法——穷举vs暴搜vs深搜

T04BF &#x1f44b;专栏: 算法|JAVA|MySQL|C语言 &#x1faf5; 小比特 大梦想 此篇文章与大家分享递归、搜索与回溯算法关于穷举vs暴搜vs深搜的专题 如果有不足的或者错误的请您指出! 目录 1.全排列1.1解析1.2题解 2.子集2.1解析2.1.1解法12.1.2解法1代码2.1.3解法22.1.4解法…