• Java工具类utils合集


    1.汉字转拼音工具类 PinYinUtils.java

    package cn.aura.utils;
    
    import net.sourceforge.pinyin4j.PinyinHelper;
    import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
    import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
    import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
    import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;
    
    /**
     * 汉字转换拼音对象
     */
    public class PinYinUtils {
    
        public static String ToPinyin(String chinese) {
            String pinyinStr = "";
            char[] newChar = chinese.toCharArray();
            HanyuPinyinOutputFormat defaultFormat = new HanyuPinyinOutputFormat();
            defaultFormat.setCaseType(HanyuPinyinCaseType.LOWERCASE);
            defaultFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
            for (int i = 0; i < newChar.length; i++) {
                if (newChar[i] > 128) {
                    try {
                        pinyinStr += PinyinHelper.toHanyuPinyinStringArray(
                                newChar[i], defaultFormat)[0];
                    } catch (BadHanyuPinyinOutputFormatCombination e) {
                        e.printStackTrace();
                    }
                } else {
                    pinyinStr += newChar[i];
                }
            }
            return pinyinStr;
        }
    }
    View Code

    2.Md5加密工具类 Md5Utils.java

    package com.gh.util;
    
    
    
    import java.math.BigInteger;
    import java.security.MessageDigest;
    import java.security.NoSuchAlgorithmException;
    
    public class Md5Utils {
        public static String md5(String plainText) {
            byte[] secretBytes = null;
            try {
                secretBytes = MessageDigest.getInstance("md5").digest(
                        plainText.getBytes());
            } catch (NoSuchAlgorithmException e) {
                throw new RuntimeException("没有md5这个算法!");
            }
            String md5code = new BigInteger(1, secretBytes).toString(16);// 16进制数字
            // 如果生成数字未满32位,需要前面补0
            for (int i = 0; i < 32 - md5code.length(); i++) {
                md5code = "0" + md5code;
            }
            return md5code;
        }
    
        public static void main(String[] args) {
            System.out.println(md5("zhanghaixihuangzhangying"));
        }
    
    }
    View Code

    3.短信发送工具类 SMSUtil.java

    package message;
    
    import com.aliyuncs.CommonRequest;
    import com.aliyuncs.CommonResponse;
    import com.aliyuncs.DefaultAcsClient;
    import com.aliyuncs.IAcsClient;
    import com.aliyuncs.exceptions.ClientException;
    import com.aliyuncs.exceptions.ServerException;
    import com.aliyuncs.http.MethodType;
    import com.aliyuncs.profile.DefaultProfile;
    import com.gh.util.CodeUtil;
    
    public class SMSUtil {
    
        public static void sendSMS(String phone,String code) {
            DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou", "LTAIsOB7XkCHTGX8", "ASy5lzMwr5KIVEUY3eDhFFijD1RkPC");
            IAcsClient client = new DefaultAcsClient(profile);
    
            CommonRequest request = new CommonRequest();
            request.setMethod(MethodType.POST);
            request.setDomain("dysmsapi.aliyuncs.com");
            request.setVersion("2017-05-25");
            
            request.setAction("SendSms");
            request.putQueryParameter("RegionId", "cn-hangzhou");
            // 发给谁  ----
            request.putQueryParameter("PhoneNumbers", phone);
            // 签名名称
            request.putQueryParameter("SignName", "英魂之刃官网");
            // 模板名称
            request.putQueryParameter("TemplateCode", "SMS_171857472");
            // 验证码 ----
            request.putQueryParameter("TemplateParam", "{"code":""+code+""}");
            try {
                CommonResponse response = client.getCommonResponse(request);
                System.out.println(response.getData());
            } catch (ServerException e) {
                e.printStackTrace();
            } catch (ClientException e) {
                e.printStackTrace();
            }
        }
    }
    View Code

    4.图片验证码工具类 ImageUtil.java

    package com.hp.p2p.util;
    
    import java.awt.Color;
    import java.awt.Font;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    import java.awt.image.BufferedImage;
    import java.io.BufferedReader;
    import java.io.FileInputStream;
    import java.io.FileReader;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.util.ArrayList;
    import java.util.List;
    import java.util.Random;
    
    import javax.imageio.ImageIO;
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    public class ImageUtil{
    
        public static void createImage(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            // 禁止缓存
            // response.setHeader("Cache-Control", "no-cache");
            // response.setHeader("Pragma", "no-cache");
            // response.setDateHeader("Expires", -1);
    
            int width = 120;
            int height = 25;
    
            // 步骤一 绘制一张内存中图片
            BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
    
            // 步骤二 图片绘制背景颜色 ---通过绘图对象
            Graphics graphics = bufferedImage.getGraphics();// 得到画图对象 --- 画笔
            // 绘制任何图形之前 都必须指定一个颜色
            graphics.setColor(getRandColor(200, 250));
            graphics.fillRect(0, 0, width, height);
    
            // 步骤三 绘制边框
            graphics.setColor(Color.WHITE);
            graphics.drawRect(0, 0, width - 1, height - 1);
    
            // 步骤四 四个随机数字
            Graphics2D graphics2d = (Graphics2D) graphics;
            // 设置输出字体
            graphics2d.setFont(new Font("宋体", Font.BOLD, 18));
    
            Random random = new Random();// 生成随机数
            String words = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
    
            // 定义x坐标
            int x = 10;
            String word = "";
            for (int i = 0; i < 4; i++) {
                int index = random.nextInt(words.length());
                // 随机颜色
                graphics2d
                        .setColor(new Color(20 + random.nextInt(110), 20 + random.nextInt(110), 20 + random.nextInt(110)));
                // 旋转 -30 --- 30度
                int jiaodu = random.nextInt(60) - 30;
                // 换算弧度
                double theta = jiaodu * Math.PI / 180;
    
                // 获得字母数字
                char c = words.charAt(index);
                word += c;
                // 将c 输出到图片
                graphics2d.rotate(theta, x, 20);
                graphics2d.drawString(String.valueOf(c), x, 20);
                graphics2d.rotate(-theta, x, 20);
                x += 30;
            }
    
            System.out.println(word);
            // 将验证码内容保存session
            request.getSession().setAttribute("checkcode_session", word);
            
            
    
            // 步骤五 绘制干扰线
            graphics.setColor(getRandColor(160, 200));
            int x1;
            int x2;
            int y1;
            int y2;
            for (int i = 0; i < 30; i++) {
                x1 = random.nextInt(width);
                x2 = random.nextInt(12);
                y1 = random.nextInt(height);
                y2 = random.nextInt(12);
                graphics.drawLine(x1, y1, x1 + x2, x2 + y2);
            }
    
            // 将上面图片输出到浏览器 ImageIO
            graphics.dispose();// 释放资源
            ImageIO.write(bufferedImage, "jpg", response.getOutputStream());
    
        }
    
    
        /**
         * 取其某一范围的color
         * 
         * @param fc
         *            int 范围参数1
         * @param bc
         *            int 范围参数2
         * @return Color
         */
        private static Color getRandColor(int fc, int bc) {
            // 取其随机颜色
            Random random = new Random();
            if (fc > 255) {
                fc = 255;
            }
            if (bc > 255) {
                bc = 255;
            }
            int r = fc + random.nextInt(bc - fc);
            int g = fc + random.nextInt(bc - fc);
            int b = fc + random.nextInt(bc - fc);
            return new Color(r, g, b);
        }
    
    }
    View Code

    5.获取随机验证码工具类 CodeUtil.java

    package com.gh.util;
    
    import java.util.Random;
    
    public class CodeUtil {
        
        
        public static String getCode(){
            String content = "qwertyuiopasdfghjklzxcvbnm1234567890ZXCVBNMQWERTYUIOPASDFGHJKL";
            Random random = new Random();
            String result = "";
            for(int i =0 ;i<4;i++){
                int index = random.nextInt(content.length());
                char c = content.charAt(index);
                result+=c;
            }
            return result;
        }
        
    
    }
    View Code

    6.发送邮件工具类 MailUtils.java

    package com.gh.util;
    
    
    
    import java.util.Properties;
    
    import javax.mail.Authenticator;
    import javax.mail.Message;
    import javax.mail.MessagingException;
    import javax.mail.PasswordAuthentication;
    import javax.mail.Session;
    import javax.mail.Transport;
    import javax.mail.internet.AddressException;
    import javax.mail.internet.InternetAddress;
    import javax.mail.internet.MimeMessage;
    import javax.mail.internet.MimeMessage.RecipientType;
    
    public class MailUtils {
        
        /* Host邮箱 发件人
         * 收件人 : 需要验证邮箱
         * 
         * 
         */
    
        //参数 email 代表的是注册用户的邮件  要发送的对象
        //参数 emailMsg 代表的是发送的信息
        public static void sendMail(String email, String emailMsg)
                throws AddressException, MessagingException {
            // 1.创建一个程序与邮件服务器会话对象 Session
    
            Properties props = new Properties();
            props.setProperty("mail.transport.protocol", "SMTP");
            props.setProperty("mail.host", "smtp.qq.com");
            props.setProperty("mail.smtp.auth", "true");// 指定验证为true
    
            // 创建验证器
            Authenticator auth = new Authenticator() {
                public PasswordAuthentication getPasswordAuthentication() {
                    //第一个参数 邮箱名 不带@。。。   
                    //第二个参数 授权码
                    return new PasswordAuthentication("fgyfqh", "hzoedmdpnwlugead");
                }
            };
    
            Session session = Session.getInstance(props, auth);
    
            // 2.创建一个Message,它相当于是邮件内容
            Message message = new MimeMessage(session);
    
            message.setFrom(new InternetAddress("fgyfqh@qq.com")); // 设置发送者
    
            message.setRecipient(RecipientType.TO, new InternetAddress(email)); // 设置发送方式与接收者
            
            //设置发送邮件的 主题
            message.setSubject("这是一封激活邮件");
            // message.setText("这是一封激活邮件,请<a href='#'>点击</a>");
    
            message.setContent(emailMsg, "text/html;charset=utf-8");
    
            // 3.创建 Transport用于将邮件发送
    
            Transport.send(message);
        }
        
    }
    View Code

    7.删除maven仓库所有lastUpdated文件 DeleteFiles.java

    package com.zxh.movieserver.configure;
    
    /**
     * @Author Eric
     * @Date 6/1/2021 9:51 AM
     */
    
    import java.io.File;
    import java.io.IOException;
    
    //列出File的一些常用操作
    public class DeleteFiles {
        /**
         * 遍历指定目录下(包括其子目录)的所有文件,并删除以 lastUpdated 结尾的文件
         * @param dir 目录的位置 path
         * @throws IOException
         */
        public static void listDirectory(File dir) throws IOException {
            if (!dir.exists())
                throw new IllegalArgumentException("目录:" + dir + "不存在.");
            if (!dir.isDirectory()) {
                throw new IllegalArgumentException(dir + " 不是目录。");
            }
            File[] files = dir.listFiles();
            if (files != null && files.length > 0) {
                for (File file : files) {
                    if (file.isDirectory())
                        //递归
                        listDirectory(file);
                    else{ // 删除以 lastUpdated 结尾的文件
                        String fileName = file.getName();
                        boolean isLastupdated = fileName.toLowerCase().endsWith("lastupdated");
                        if (isLastupdated){
                            boolean is_delete = file.delete();
                            System.out.println("删除的文件名 => " + file.getName() + "  || 是否删除成功? ==> " + is_delete);
                        }
                    }
                }
            }
        }
    
        public static void main(String[] args) throws IOException {
            // 指定maven的本地仓库
            listDirectory(new File("D:\repository"));
        }
    }
    View Code

    8.生成token字符串 JwtUtils.java

    package com.gh.mp.edu.utils;
    
    import io.jsonwebtoken.Claims;
    import io.jsonwebtoken.Jws;
    import io.jsonwebtoken.Jwts;
    import io.jsonwebtoken.SignatureAlgorithm;
    import org.springframework.util.StringUtils;
    
    import javax.servlet.http.HttpServletRequest;
    import java.util.Date;
    
    /**
     * @author helen
     * @since 2019/10/16
     */
    public class JwtUtils {
    
        //常量
        public static final long EXPIRE = 1000 * 60 * 60 * 24; //token过期时间
        public static final String APP_SECRET = "ukc8BDbRigUDaY6pZFfWus2jZWLPHO"; //秘钥
    
        //生成token字符串的方法
        public static String getJwtToken(String id, String nickname){
    
            String JwtToken = Jwts.builder()
                    .setHeaderParam("typ", "JWT")
                    .setHeaderParam("alg", "HS256")
    
                    .setSubject("guli-user")
                    .setIssuedAt(new Date())
                    .setExpiration(new Date(System.currentTimeMillis() + EXPIRE))
    
                    .claim("id", id)  //设置token主体部分 ,存储用户信息
                    .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 {
                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");
        }
    
        public static String getMemberIdByToken(String token) {
            if(StringUtils.isEmpty(token)) return "";
            Jws<Claims> claimsJws = Jwts.parser().setSigningKey(APP_SECRET).parseClaimsJws(token);
            Claims claims = claimsJws.getBody();
            return (String)claims.get("id");
        }
    }
    View Code

    9.发送http请求工具类HttpClient.java

    package com.gh.mp.eduOrder.utils;
    
    import org.apache.http.Consts;
    import org.apache.http.HttpEntity;
    import org.apache.http.NameValuePair;
    import org.apache.http.client.ClientProtocolException;
    import org.apache.http.client.entity.UrlEncodedFormEntity;
    import org.apache.http.client.methods.*;
    import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
    import org.apache.http.conn.ssl.SSLContextBuilder;
    import org.apache.http.conn.ssl.TrustStrategy;
    import org.apache.http.entity.StringEntity;
    import org.apache.http.impl.client.CloseableHttpClient;
    import org.apache.http.impl.client.HttpClients;
    import org.apache.http.message.BasicNameValuePair;
    import org.apache.http.util.EntityUtils;
    
    import javax.net.ssl.SSLContext;
    import java.io.IOException;
    import java.security.cert.CertificateException;
    import java.security.cert.X509Certificate;
    import java.text.ParseException;
    import java.util.HashMap;
    import java.util.LinkedList;
    import java.util.List;
    import java.util.Map;
    
    /**
     * http请求客户端
     * 
     * @author qy
     * 
     */
    public class HttpClient {
        private String url;
        private Map<String, String> param;
        private int statusCode;
        private String content;
        private String xmlParam;
        private boolean isHttps;
    
        public boolean isHttps() {
            return isHttps;
        }
    
        public void setHttps(boolean isHttps) {
            this.isHttps = isHttps;
        }
    
        public String getXmlParam() {
            return xmlParam;
        }
    
        public void setXmlParam(String xmlParam) {
            this.xmlParam = xmlParam;
        }
    
        public HttpClient(String url, Map<String, String> param) {
            this.url = url;
            this.param = param;
        }
    
        public HttpClient(String url) {
            this.url = url;
        }
    
        public void setParameter(Map<String, String> map) {
            param = map;
        }
    
        public void addParameter(String key, String value) {
            if (param == null)
                param = new HashMap<String, String>();
            param.put(key, value);
        }
    
        public void post() throws ClientProtocolException, IOException {
            HttpPost http = new HttpPost(url);
            setEntity(http);
            execute(http);
        }
    
        public void put() throws ClientProtocolException, IOException {
            HttpPut http = new HttpPut(url);
            setEntity(http);
            execute(http);
        }
    
        public void get() throws ClientProtocolException, IOException {
            if (param != null) {
                StringBuilder url = new StringBuilder(this.url);
                boolean isFirst = true;
                for (String key : param.keySet()) {
                    if (isFirst)
                        url.append("?");
                    else
                        url.append("&");
                    url.append(key).append("=").append(param.get(key));
                }
                this.url = url.toString();
            }
            HttpGet http = new HttpGet(url);
            execute(http);
        }
    
        /**
         * set http post,put param
         */
        private void setEntity(HttpEntityEnclosingRequestBase http) {
            if (param != null) {
                List<NameValuePair> nvps = new LinkedList<NameValuePair>();
                for (String key : param.keySet())
                    nvps.add(new BasicNameValuePair(key, param.get(key))); // 参数
                http.setEntity(new UrlEncodedFormEntity(nvps, Consts.UTF_8)); // 设置参数
            }
            if (xmlParam != null) {
                http.setEntity(new StringEntity(xmlParam, Consts.UTF_8));
            }
        }
    
        private void execute(HttpUriRequest http) throws ClientProtocolException,
                IOException {
            CloseableHttpClient httpClient = null;
            try {
                if (isHttps) {
                    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);
                    httpClient = HttpClients.custom().setSSLSocketFactory(sslsf)
                            .build();
                } else {
                    httpClient = HttpClients.createDefault();
                }
                CloseableHttpResponse response = httpClient.execute(http);
                try {
                    if (response != null) {
                        if (response.getStatusLine() != null)
                            statusCode = response.getStatusLine().getStatusCode();
                        HttpEntity entity = response.getEntity();
                        // 响应内容
                        content = EntityUtils.toString(entity, Consts.UTF_8);
                    }
                } finally {
                    response.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                httpClient.close();
            }
        }
    
        public int getStatusCode() {
            return statusCode;
        }
    
        public String getContent() throws ParseException, IOException {
            return content;
        }
    
    }
    View Code

    10.日期操作工具类DateUtil.java

    package com.gh.mp.staservice.utils;
    
    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;
    
    import java.text.DateFormat;
    import java.text.ParseException;
    import java.text.SimpleDateFormat;
    import java.util.ArrayList;
    import java.util.Calendar;
    import java.util.Date;
    import java.util.List;
    
    /**
     * 日期操作工具类
     *
     * @author qy
     * @since 1.0
     */
    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)));
        }
    }
    View Code

    11.微信相关的静态类WeChatUtil.java

    微信公众开发文档 http://caibaojian.com/wxwiki/59e02a7ec96037a68023675b64a5c153c5a22471.html

    package com.cyou.system.utils;
    
    import com.alibaba.fastjson.JSONArray;
    import com.alibaba.fastjson.JSONException;
    import com.alibaba.fastjson.JSONObject;
    import com.cyou.system.dto.wechat.MaterialParamDto;
    import com.platform.common.exceptions.BusinessException;
    import lombok.extern.slf4j.Slf4j;
    import org.apache.http.HttpEntity;
    import org.apache.http.HttpResponse;
    import org.apache.http.client.methods.HttpGet;
    import org.apache.http.impl.client.CloseableHttpClient;
    import org.apache.http.impl.client.HttpClients;
    import org.apache.http.util.EntityUtils;
    
    import javax.net.ssl.*;
    import java.io.*;
    import java.net.ConnectException;
    import java.net.URL;
    import java.security.cert.CertificateException;
    import java.security.cert.X509Certificate;
    
    /**
     * 微信相关的静态方法类
     * 
     * @author 蜜瓜
     *
     *         2019年11月19日
     */
    @Slf4j
    public class WeChatUtil {
    
        // 凭证获取
        // 获取access_token
        public final static String token_url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET";
        // 获取素材列表
        public final static String MATERIAL = "https://api.weixin.qq.com/cgi-bin/material/batchget_material?access_token=ACCESS_TOKEN";
    
        // 获取素材总数
        public final static String COUNT = "https://api.weixin.qq.com/cgi-bin/material/get_materialcount?access_token=ACCESS_TOKEN";
    
    
        public static class X509TrustManager implements javax.net.ssl.X509TrustManager{
    
            @Override
            public void checkClientTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
    
            }
    
            @Override
            public void checkServerTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
    
            }
    
            @Override
            public X509Certificate[] getAcceptedIssuers() {
                return new X509Certificate[0];
            }
        }
    
        public static JSONObject doGet(String url) throws IOException {
            CloseableHttpClient httpClient = HttpClients.createDefault();
            HttpGet httpGet = new HttpGet(url);
            JSONObject jsonObject = null;
            HttpResponse response = httpClient.execute(httpGet);
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                String result = EntityUtils.toString(entity, "UTF-8");
                jsonObject = JSONObject.parseObject(result);
            }
            return jsonObject;
        }
    
        /**
         * 获取接口访问凭证
         * 
         * @param appId     凭证
         * @param appSecret 密钥
         * @return
         * @throws IOException
         */
        public static String getToken(String appId, String appSecret) throws IOException {
            String token = null;
            // 替换相应的参数
            String requestUrl = token_url.replace("APPID", appId).replace("APPSECRET", appSecret);
            // 发起GET请求获取凭证
            JSONObject jsonObject = doGet(requestUrl);
            token = jsonObject.getString("access_token");
            if (null == token) {
                log.error("获取token失败 返回的内容为:{}", jsonObject.toString());
                throw new BusinessException("此公众号配置有误!");
            }
            return token;
        }
    
        /**
         * 发送https请求
         * 
         * @param requestUrl    请求地址
         * @param requestMethod 请求方式(GET、POST)
         * @param outputStr     提交的数据
         * @return JSONObject(通过JSONObject.get(key)的方式获取json对象的属性值)
         */
        public static JSONObject httpsRequest(String requestUrl, String requestMethod, String outputStr) {
            JSONObject jsonObject = null;
            try {
                // 创建SSLContext对象,并使用我们指定的信任管理器初始化
                TrustManager[] tm = { new X509TrustManager() };
                SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
                sslContext.init(null, tm, new java.security.SecureRandom());
                // 从上述SSLContext对象中得到SSLSocketFactory对象
                SSLSocketFactory ssf = sslContext.getSocketFactory();
    
                URL url = new URL(requestUrl);
                HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
                conn.setSSLSocketFactory(ssf);
    
                conn.setDoOutput(true);
                conn.setDoInput(true);
                conn.setUseCaches(false);
                // 设置请求方式(GET/POST)
                conn.setRequestMethod(requestMethod);
    
                // 当outputStr不为null时向输出流写数据
                if (null != outputStr && !"".equals(outputStr)) {
                    OutputStream outputStream = conn.getOutputStream();
                    // 注意编码格式
                    outputStream.write(outputStr.getBytes("UTF-8"));
                    outputStream.close();
                }
    
                // 从输入流读取返回内容
                InputStream inputStream = conn.getInputStream();
                InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
                BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
                String str = null;
                StringBuffer buffer = new StringBuffer();
                while ((str = bufferedReader.readLine()) != null) {
                    buffer.append(str);
                }
    
                // 释放资源
                bufferedReader.close();
                inputStreamReader.close();
                inputStream.close();
                inputStream = null;
                conn.disconnect();
                jsonObject = JSONObject.parseObject(buffer.toString());
            } catch (ConnectException ce) {
                log.error("连接超时", ce);
            } catch (Exception e) {
                log.error("https请求异常", e);
            }
            return jsonObject;
        }
        
        /**
         * 测试获取素材的第一张图片
         * 
         * @return
         * @throws IOException
         * @param accessToken ,requestUrl获取图文素材URL
         */
        public static String getImgage(String accessToken, String requestUrl) throws IOException {
            String url = null;
            MaterialParamDto para = new MaterialParamDto();// 调用接口所需要的参数实体类
            para.setType("image");// 素材的类型
            para.setOffset(0);// 从全部素材的该偏移位置开始返回,0表示从第一个素材 返回
            para.setCount(1); // 返回素材的数量,取值在1到20之间
            JSONObject jsonObject = new JSONObject();
            JSONObject paraJson = new JSONObject();
            paraJson = (JSONObject) JSONObject.toJSON(para); // 发送https请求(请求的路径,方式,所携带的参数)
            jsonObject = httpsRequest(requestUrl, "POST", paraJson.toString()); // 从公众号获取数据
            /*公众号图片素材数据格式
             * {
               "total_count": TOTAL_COUNT,
               "item_count": ITEM_COUNT,
               "item": [{
                   "media_id": MEDIA_ID,
                   "name": NAME,
                   "update_time": UPDATE_TIME,
                   "url":URL
               },
               //可能会有多个素材
               ]
            }*/
            // 如果请求成功
            if (null != jsonObject) {
                try {
                    JSONArray jsonArray = jsonObject.getJSONArray("item");
    
                    JSONObject json = (JSONObject) jsonArray.get(0);
                    url = json.getString("url");
    
                } catch (JSONException e) {
                    accessToken = null;
                    // 获取Material失败
                    log.error("获取Material失败 errcode:{} errmsg:{}", jsonObject.get("errcode"),
                            jsonObject.getString("errmsg"));
                }
            }
    
            return url;
        }
    
        public static String getImgages(String accessToken, String requestUrl) throws IOException {
            String url = null;
            MaterialParamDto para = new MaterialParamDto();// 调用接口所需要的参数实体类
            para.setType("image");// 素材的类型
            para.setOffset(0);// 从全部素材的该偏移位置开始返回,0表示从第一个素材 返回
            para.setCount(1); // 返回素材的数量,取值在1到20之间
            JSONObject jsonObject = new JSONObject();
            JSONObject paraJson = new JSONObject();
            paraJson = (JSONObject) JSONObject.toJSON(para); // 发送https请求(请求的路径,方式,所携带的参数)
            jsonObject = httpsRequest(requestUrl, "POST", paraJson.toString()); // 从公众号获取数据
            /*公众号图片素材数据格式
             * {
               "total_count": TOTAL_COUNT,
               "item_count": ITEM_COUNT,
               "item": [{
                   "media_id": MEDIA_ID,
                   "name": NAME,
                   "update_time": UPDATE_TIME,
                   "url":URL
               },
               //可能会有多个素材
               ]
            }*/
            // 如果请求成功
            if (null != jsonObject) {
                try {
                    JSONArray jsonArray = jsonObject.getJSONArray("item");
    
                    JSONObject json = (JSONObject) jsonArray.get(0);
                    url = json.getString("url");
    
                } catch (JSONException e) {
                    accessToken = null;
                    // 获取Material失败
                    log.error("获取Material失败 errcode:{} errmsg:{}", jsonObject.get("errcode"),
                            jsonObject.getString("errmsg"));
                }
            }
    
            return url;
        }
    }
    View Code

    一点点学习,一丝丝进步。不懈怠,才不会被时代所淘汰!

  • 相关阅读:
    flutter 右滑返回上一页
    flutter 的Animation简单了解
    Flutter Offstage、Visibility隐藏/可见
    flutter手势
    Flutter生命周期
    flutter 路由动画
    flutter 保持页面状态
    flutter 不规则底部工具栏实现
    flutter 主页面底部导航栏实现以及主题风格设置
    flutter DropdownButton使用
  • 原文地址:https://www.cnblogs.com/fqh2020/p/14819666.html
Copyright © 2020-2023  润新知