常用工具类

1.HtmlUtil

向页面输入String,会自动转为json格式:

package com.zys.training.util;


import com.fasterxml.jackson.databind.ObjectMapper;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;


/**
 * 向页面输出String
 * @author yushizhong
 */
public class HtmlUtil {

    /**
     * 输出string
     * @param response
     * @param jsonStr
     */
    public static void writerJson(HttpServletResponse response, String jsonStr) {
        writer(response, jsonStr);
    }

    public static void writerJson(HttpServletResponse response, Object object) throws Exception {
        ObjectMapper mapper = new ObjectMapper();
        String jsonString = mapper.writeValueAsString(object)  ;
        writer(response,  jsonString);

    }

    private static void writer(HttpServletResponse response, String str)   {
        try {
            // 设置页面不缓存
            response.setHeader("Pragma", "No-cache");
            response.setHeader("Cache-Control", "no-cache");
            response.setHeader("Access-Control-Allow-Origin","*");
            response.setCharacterEncoding("UTF-8");
            PrintWriter out = null;
            out = response.getWriter();
            out.print(str);
            out.flush();
            out.close();
        } catch ( Exception ex){
            ex.printStackTrace();
        }
    }

    public static Map<String, String> getParameterMap(HttpServletRequest request) {
        // 参数Map
        Map properties = request.getParameterMap();
        // 返回值Map
        Map<String, String> returnMap = new HashMap<String, String>();
        Iterator entries = properties.entrySet().iterator();
        Map.Entry entry;
        String name = "";
        String value = "";
        while (entries.hasNext()) {
            entry = (Map.Entry) entries.next();
            name = (String) entry.getKey();
            Object valueObj = entry.getValue();
            if (null == valueObj) {
                value = "";
            } else if (valueObj instanceof String[]) {
                String[] values = (String[]) valueObj;
                for (int i = 0; i < values.length; i++) {
                    value = values[i] + ",";
                }
                value = value.substring(0, value.length() - 1);
            } else {
                value = valueObj.toString();
            }
            returnMap.put(name, value);
        }
        return returnMap;
    }

}
HtmlUtil源码

调用方式:

@RequestMapping("/get")
    public void get(HttpServletResponse response){
        response.setContentType("application/json");
        HtmlUtil.writerJson(response, "hello");
    }

2.Md5Utils

md5加密

package com.example.springsecurity.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;
    }


}
Md5Utils源码

调用方式:

Md5Utils.md5("123")

3.ImageUtil

图片验证码,将验证码内容保存session中

package com.gh.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

调用方式:

@GetMapping("/getImageCode")
    public void getImageCode(HttpServletRequest request, HttpServletResponse response) throws Exception {
        imageUtil.createImage(request, response);
    }

4.SmsService

短信验证码,用于验证短信

package com.zys.springboottestexample.service;

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 lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
/*
pom.xml
<dependency>
  <groupId>com.aliyun</groupId>
  <artifactId>aliyun-java-sdk-core</artifactId>
  <version>4.0.3</version>
</dependency>
*/

/**
 * 发送短信
 */
@Slf4j
@Component
public class SmsService {

    //域名
    private static String domain = "dysmsapi.aliyuncs.com";
    //执行动作
    private static String action = "SendSms";
    //版本号,api发布的为准
    private static String version = "2017-05-25";
    //地区编码
    private static String regionId = "cn-hangzhou";
    //签名名称
    private static String signName = "生活网站后台管理系统";
    //模版CODE,默认的
    private static String defaultTemplateCode = "SMS_181855626";


    @Value("${sms.accessKeyId}")
    private String accessKeyId;

    @Value("${sms.secret}")
    private String secret;


    public void sendMsgCode(String phone, String code) {
        this.sendCode(phone, code, defaultTemplateCode);
    }

    private void sendCode(String phone, String code, String templateCode) {
        try {
            DefaultProfile profile = DefaultProfile.getProfile(regionId, accessKeyId, secret);
            IAcsClient client = new DefaultAcsClient(profile);
            CommonRequest request = new CommonRequest();
            request.setMethod(MethodType.POST);
            request.setDomain(domain);
            request.setAction(action);
            request.setVersion(version);
            request.putQueryParameter("RegionId", regionId);
            request.putQueryParameter("PhoneNumbers", phone);
            request.putQueryParameter("SignName", signName);
            request.putQueryParameter("TemplateCode", templateCode);
            request.putQueryParameter("TemplateParam", "{\"code\":\"" + code + "\"}");
            CommonResponse response = client.getCommonResponse(request);
            log.info("发送短信结果:" + response.getData());
        } catch (Exception e) {
            e.printStackTrace();
            log.error("短信发送异常:" + e.getMessage());
        }
    }
}
View Code

具体用法:将代码中的依赖添加到项目的依赖中,在配置文件中配置keyId和秘钥

sms:
  accessKeyId: 4545484518888
  secret: 2151584552

然后注入并调用这个方法,传入验证码和手机号即可。对应验证和上面的图片验证码类型,存入redis。

调用方式:

@Autowired
private SmsService smsService;

.....


smsService.sendMsg("17012122353","123456")

5.CodeUtil

生成指定位数的字符串,包含数组和字母。

package com.example.springsecurity.util;

import java.util.Random;

public class CodeUtil {
    
    
    public static String getCode(int len){
        String content = "qwertyuiopasdfghjklzxcvbnm1234567890ZXCVBNMQWERTYUIOPASDFGHJKL";
        Random random = new Random();
        String result = "";
        for(int i =0 ;i<len;i++){
            int index = random.nextInt(content.length());
            char c = content.charAt(index);
            result+=c;
        }
        return result;
    }
    

}
View Code

调用方式:

 CodeUtil.getCode(6)

6.DeleteFileUtil

删除文件及文件夹。

package com.zys.training.util;

import java.io.File;

/**
 * @Author: yushizhong
 * @Date: 2020/2/21 12:07
 * @Title: 文件及文件夹的删除
 */
public class DeleteFileUtil {

    //文件的删除
    public static boolean deleteFile(String pathname) {
        boolean result = false;
        File file = new File(pathname);
        if (file.exists()) {
            file.delete();
            result = true;
        }
        return result;
    }

    //文件夹的删除(强制删除)
    public static void deleteAllFilesOfDir(File path) {
        if (null != path) {
            if (!path.exists())
                return;
            if (path.isFile()) {
                boolean result = path.delete();
                int tryCount = 0;
                while (!result && tryCount++ < 10) {
                    System.gc(); // 回收资源
                    result = path.delete();
                }
            }
            File[] files = path.listFiles();
            if (null != files) {
                for (int i = 0; i < files.length; i++) {
                    deleteAllFilesOfDir(files[i]);
                }
            }
            path.delete();
        }
    }
}
View Code

调用方式:

DeleteFileUtil.deleteFile(文件路径)
DeleteFileUtil.deleteAllFilesOfDir(文件夹路径)

7.ExcelResolveUtil

解析excel内容,返回一个JOSNArray。

package com.example.uploaddemo.util;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.poi.hssf.usermodel.HSSFDateUtil;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.text.DateFormat;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author: yushizhong
 * @Date: 2020/2/22 12:07
 * @Title: 解析excel内容
 */
public class ExcelResolveUtil {

    public final static String XLSX = ".xlsx";
    public final static String XLS = ".xls";

    /**
     * 获取Excel文件(.xls和.xlsx都支持)
     *
     * @param file 文件对象
     * @return 解析excle后的Json数据
     */
    public static JSONArray readExcel(File file ) throws Exception {
        int res = checkFile(file);
        if (res == 0) {
            System.out.println("File not found");
        } else if (res == 1) {
            return readXLSX(file );
        } else if (res == 2) {
            return readXLS(file );
        }
        JSONArray array = new JSONArray();
        return array;
    }

    /**
     * 判断File文件的类型
     *
     * @param file 传入的文件
     * @return 0-文件为空,1-XLSX文件,2-XLS文件,3-其他文件
     */
    public static int checkFile(File file) {
        if (file == null) {
            return 0;
        }
        String fileName = file.getName();
        if (fileName.endsWith(XLSX)) {
            return 1;
        }
        if (fileName.endsWith(XLS)) {
            return 2;
        }
        return 3;
    }

    /**
     * 读取XLSX文件
     *
     * @param file
     * @return
     * @throws IOException
     * @throws InvalidFormatException
     */
    public static JSONArray readXLSX(File file ) throws InvalidFormatException, IOException, InvalidFormatException {
        Workbook book = new XSSFWorkbook(file);
        Sheet sheet = book.getSheetAt(0);
        return read(sheet, book );
    }

    /**
     * 读取XLS文件
     *
     * @param file 文件对象
     * @throws IOException
     * @throws FileNotFoundException
     */
    public static JSONArray readXLS(File file ) throws FileNotFoundException, IOException {
        POIFSFileSystem poifsFileSystem = new POIFSFileSystem(new FileInputStream(file));
        Workbook book = new HSSFWorkbook(poifsFileSystem);
        Sheet sheet = book.getSheetAt(0);
        return read(sheet, book );
    }

    /**
     * 解析数据
     *
     * @param sheet 表格sheet对象
     * @param book  用于流关闭
     * @return
     * @throws IOException
     */
    public static JSONArray read(Sheet sheet, Workbook book ) throws IOException {
        int rowStart = sheet.getFirstRowNum();    // 首行下标
        int rowEnd = sheet.getLastRowNum();    // 尾行下标
        // 如果首行与尾行相同,表明只有一行,直接返回空数组
        if (rowStart == rowEnd) {
            book.close();
            return new JSONArray();
        }
        // 获取第一行JSON对象键
        Row firstRow = sheet.getRow(rowStart);
        int cellStart = firstRow.getFirstCellNum();
        int cellEnd = firstRow.getLastCellNum();
        Map<Integer, String> keyMap = new HashMap<Integer, String>();
        for (int j = cellStart; j < cellEnd; j++) {
            keyMap.put(j, getValue(firstRow.getCell(j), rowStart, j, book, true));
        }
        // 获取每行JSON对象的值
        JSONArray array = new JSONArray();
        for (int i = rowStart + 1; i <= rowEnd; i++) {
            Row eachRow = sheet.getRow(i);
            JSONObject obj = new JSONObject();
            StringBuffer sb = new StringBuffer();
            for (int k = cellStart; k < cellEnd; k++) {
                if (eachRow != null) {
                    String val = getValue(eachRow.getCell(k), i, k, book, false);
                    sb.append(val);        // 所有数据添加到里面,用于判断该行是否为空
                    obj.put(keyMap.get(k), val);
                }
            }
            if (sb.toString().length() > 0) {
                array.add(obj);
            }
        }
        book.close();
        return array;
    }

    /**
     * 获取每个单元格的数据
     *
     * @param cell   单元格对象
     * @param rowNum 第几行
     * @param index  该行第几个
     * @param book   主要用于关闭流
     * @param isKey  是否为键:true-是,false-不是。 如果解析Json键,值为空时报错;如果不是Json键,值为空不报错
     * @return
     * @throws IOException
     */
    public static String getValue(Cell cell, int rowNum, int index, Workbook book, boolean isKey) throws IOException {
        // 空白或空
        if (cell == null || cell.getCellType() == Cell.CELL_TYPE_BLANK) {
            if (isKey) {
                book.close();
                throw new NullPointerException(String.format("the key on row %s index %s is null ", ++rowNum, ++index));
            } else {
                return "";
            }
        }
        // 0. 数字 类型
        if (cell.getCellType() == Cell.CELL_TYPE_NUMERIC) {
            if (HSSFDateUtil.isCellDateFormatted(cell)) {
                Date date = cell.getDateCellValue();
                DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                return df.format(date);
            }
            //防止当作数字而导致最后的0丢失
            DecimalFormat df = new DecimalFormat("0");
            String val = df.format(cell.getNumericCellValue());
            val = val.toUpperCase();
            if (val.contains("E")) {
                val = val.split("E")[0].replace(".", "");
            }
            return val;
        }
        // 1. String类型
        if (cell.getCellType() == Cell.CELL_TYPE_STRING) {
            String val = cell.getStringCellValue();
            if (val == null || val.trim().length() == 0) {
                if (book != null) {
                    book.close();
                }
                return "";
            }
            return val.trim();
        }
        // 2. 公式 CELL_TYPE_FORMULA
        if (cell.getCellType() == Cell.CELL_TYPE_FORMULA) {
            return cell.getStringCellValue();
        }
        // 4. 布尔值 CELL_TYPE_BOOLEAN
        if (cell.getCellType() == Cell.CELL_TYPE_BOOLEAN) {
            return cell.getBooleanCellValue() + "";
        }
        // 5.    错误 CELL_TYPE_ERROR
        return "";
    }



}
View Code

依赖jar:

  <!-- POI,excel解析相关 -->
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi</artifactId>
            <version>3.17</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.apache.poi/poi-ooxml -->
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml</artifactId>
            <version>3.17</version>
        </dependency>
        <dependency>
            <groupId>net.sf.json-lib</groupId>
            <artifactId>json-lib</artifactId>
            <version>2.4</version>
            <classifier>jdk15</classifier>
        </dependency>
View Code

调用方式:

JSONArray jsonArray = ExcelResolveUtil.readExcel(new File("D:\\files\\文件导入\\成绩.xls"));

8.DiskFreeUtils

获取磁盘使用信息。

package com.zys.training.util;

import java.io.File;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class DiskFreeUtils {
    private static DecimalFormat DECIMALFORMAT = new DecimalFormat("#.##");
 
    /**
     * 获取磁盘使用信息
     * @return
     */
    public static List<Map<String, String>> getInfo() {
        List<Map<String, String>> list = new ArrayList<Map<String, String>>();
        File[] roots = File.listRoots();// 获取磁盘分区列表
        for (File file : roots) {
            Map<String, String> map = new HashMap<String, String>();
            long freeSpace=file.getFreeSpace();
            long totalSpace=file.getTotalSpace();
            long usableSpace=totalSpace-freeSpace;
            map.put("path", file.getPath().split(":")[0]);
            map.put("freeSpace", freeSpace / 1024 / 1024 / 1024 + "G");// 空闲空间
            map.put("usableSpace", usableSpace / 1024 / 1024 / 1024 + "G");// 可用空间
            map.put("totalSpace",totalSpace / 1024 / 1024 / 1024 + "G");// 总空间
            map.put("percent", DECIMALFORMAT.format(((double)usableSpace/(double)totalSpace)*100)+"%");// 总空间
            list.add(map);
        }
        return list;
    }
 

}
View Code

调用方式:

List<Map<String, String>> map=DiskFreeUtils.getInfo();

9.PropertiesUtil

读取.properties配置文件的内容至Map中。

package com.zys.training.util;

import java.io.IOException;
import java.io.InputStream;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

/**
 * 读取.properties配置文件的内容至Map中
 */
public class PropertiesUtil {

    /**
     * 读取.properties配置文件的内容至Map
     *
     * @param propertiesFile
     * @return
     * @throws IOException
     */
    public static Map read(String propertiesFile) throws Exception {
        try {
            if (!(propertiesFile.indexOf("properties") > 0)) {
                propertiesFile = propertiesFile + ".properties";
            }
            InputStream inStream = Thread.currentThread().getContextClassLoader().getResourceAsStream(propertiesFile);
            Properties p = new Properties();
            p.load(inStream);

            Map<Object, Object> map = properties2map(p);
            return map;
        } catch (IOException e) {
            throw new Exception(e);
        }
    }

    /**
     * 将属性文件转为map
     *
     * @param prop
     * @return
     */
    public static Map properties2map(Properties prop) {
        Map<Object, Object> map = new HashMap<Object, Object>();
        Enumeration enu = prop.keys();
        while (enu.hasMoreElements()) {
            Object obj = enu.nextElement();
            Object objv = prop.get(obj);
            map.put(obj, objv);
        }
        return map;
    }
}
View Code

调用方式:

Map read = PropertiesUtil.read("application.properties");

10.HttpClient

使用java发送get/post请求

导入坐标

   <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.5.3</version>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.58</version>
        </dependency>
View Code

添加工具类

package com.example.task.test;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.client.methods.RequestBuilder;
import org.apache.http.config.ConnectionConfig;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * @author zhongyushi
 * @date 2020/7/21 0021
 * @dec 使用apache的http协议发送请求
 */
@Component
public class HttpClient {

    private ConnectionConfig connectionConfig = ConnectionConfig.custom().setBufferSize(4128).build();
    private CloseableHttpClient httpClient = HttpClients.custom().setDefaultConnectionConfig(connectionConfig).build();

    /**
     * get请求,返回JSONObject
     */
    public JSONObject get(String url) {
        try {
            RequestBuilder builder = RequestBuilder.get(url);
            HttpUriRequest request = builder.build();
            return httpClient.execute(request, getResponseHandler());
        } catch (Exception e) {
            e.printStackTrace();
            JSONObject error = new JSONObject();
            error.put("msg", e.getMessage());
            return error;
        }
    }

    /**
     * post请求-返回JSONObject
     */
    public JSONObject post(String url, String json) {
        try {
            HttpPost httpPost = new HttpPost(url);
            //设置请求体
            if (json != null && json != "") {
                //解决中文乱码问题
                StringEntity entity = new StringEntity(json, "utf-8");
                entity.setContentEncoding("UTF-8");
                entity.setContentType("application/json");
                httpPost.setEntity(entity);
            }
            return httpClient.execute(httpPost, getResponseHandler());
        } catch (Exception e) {
            JSONObject error = new JSONObject();
            error.put("msg", e.getMessage());
            e.printStackTrace();
            return error;
        }
    }

    /**
     * 指定响应返回类型=JSONObject
     */
    private ResponseHandler<JSONObject> getResponseHandler() {
        ResponseHandler<JSONObject> handler = new ResponseHandler<JSONObject>() {
            public JSONObject handleResponse(HttpResponse response) throws IOException {
                HttpEntity entity = response.getEntity();
                if (entity != null) {
                    String json = EntityUtils.toString(entity, "UTF-8");
                    return JSON.parseObject(json);
                }
                return null;
            }
        };
        return handler;
    }
}
View Code

调用方式:

private String url="https://autumnfish.cn/api"; 
 //注入写的方法
    @Autowired
    private HttpClient httpClient;

    @GetMapping("/get")
    public JSONObject get(){
        JSONObject jsonObject = httpClient.get(url + "/joke/list?num=" + 10);
        return jsonObject;
    }

    @PostMapping("/post")
    public JSONObject post(){
        Map<String,Object> map=new HashMap<>();
        map.put("username","张三111");
        JSONObject jsonObject = httpClient.post(url + "/user/reg", JSON.toJSONString(map));
        return jsonObject;
    }

11.dateFormat

格式化日期,根据指定的格式进行格式化。
//格式化日期函数,YYYY-mm-dd HH:MM:SS或yyyy-mm-dd HH:MM:ss
function dateFormat(fmt, date) {
    if (fmt == null) {
        fmt = 'YYYY-mm-dd HH:MM:SS'
    }
    if (date != '') {
        let ret
        const opt = {
            "Y+": date.getFullYear().toString(), //
            "y+": date.getFullYear().toString(), //
            "m+": (date.getMonth() + 1).toString(), //
            "d+": date.getDate().toString(), //
            "H+": date.getHours().toString(), //
            "M+": date.getMinutes().toString(), //
            "S+": date.getSeconds().toString(), //
            "s+": date.getSeconds().toString() //// 有其他格式化字符需求可以继续添加,必须转化成字符串
        }
        for (let k in opt) {
            ret = new RegExp("(" + k + ")").exec(fmt)
            if (ret) {
                fmt = fmt.replace(ret[1], (ret[1].length == 1) ? (opt[k]) : (opt[k].padStart(ret[1].length, "0")))
            }
        }
    } else {
        fmt = 'date不能为空'
    }
    return fmt
}

调用方式

dateFormat('YYYY-mm-dd HH:MM:SS',new Date())
//
dateFormat('yyyy-mm-dd HH:MM:ss',new Date())

12.preDate

计算当前时间的前几天时间。
function preDate(flag, day) {
    let fotmat = null
    if (flag == null) {
        fotmat = 'YYYY-mm-dd'
    } else if (flag == 0) {
        fotmat = 'YYYY-mm-dd HH:MM'
    }
    //传入参数不合法,就设置默认是30天
    if (!Number.isInteger(day)) {
        day = 30
    }
    const date = new Date(new Date().getTime() - 3600 * 1000 * 24 * day)
    return date
}

调用方式

preDate(null,30)

如果需要再进行时间的格式化,再调用上面的日期格式化函数即可。

 。

就是这么简单,你学废了吗?感觉有用的话,给笔者点个赞吧 !
原文地址:https://www.cnblogs.com/zys2019/p/12085327.html