java实用工具类

Java中有许多内置和第三方实用工具类可以大大提高开发效率。以下是一些常用的实用工具类分类和示例

时间工具类:

java 复制代码
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

public class TimeUtils {

    private static final DateTimeFormatter FORMATTER = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");

    private static final DateTimeFormatter STANDARD_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

    public static String getTimestamp() {
        return LocalDateTime.now().format(FORMATTER);
    }
    
    /**
     * 获取标准格式的时间戳 (yyyy-MM-dd HH:mm:ss)
     * @return 格式化后的时间字符串
     */
    public static String getStandardTimestamp() {
        return LocalDateTime.now().format(STANDARD_FORMATTER);
    }

}

生成随机ID工具类

java 复制代码
import java.util.UUID;

public class UuidUtils {

    public static String getUUID() {
        return UUID.randomUUID().toString().replace("-", "");
    }

}

JSON工具类:

java 复制代码
import java.lang.reflect.Type;

import cn.hutool.json.JSONUtil;

public class JsonUtil {

	/**
	 * JSON串转成对象
	 * 
	 * @param jsonStr
	 * @param cls
	 * @return
	 */
	public static <T> T fromJson(String jsonStr, Class<T> cls) {
		try {
			if (null == jsonStr || jsonStr.trim().length() == 0) {
				return null;
			}
			return JSONUtil.toBean(jsonStr, cls);
		} catch (Exception e) {
			return null;
		}
	}

	/**
	 * JSON串转成对象
	 * 
	 * @param jsonStr
	 * @param typeOfT
	 * @return
	 */
	public static Object fromJson(String jsonStr, Type typeOfT) {
		if (null == jsonStr || jsonStr.trim().length() == 0) {
			return null;
		}
		return JSONUtil.toBean(jsonStr, typeOfT, true);
	}

	/**
	 * 对象转JSON串
	 * 
	 * @param t
	 * @return
	 */
	public static <T> String toJson(T obj) {
		if (obj == null) {
			return null;
		}
		return JSONUtil.toJsonStr(obj);
	}
}

Http请求工具类

java 复制代码
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.InetAddress;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.net.UnknownHostException;
import java.util.Map;

import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.util.StringUtils;
import org.springframework.web.client.RestTemplate;

import cn.hutool.core.collection.CollectionUtil;
import lombok.extern.slf4j.Slf4j;

/**
 * http请求
 */
@Slf4j
public class HttpUtils {
	
	public static String doGet(String url) {
		return doGet(url, null);
	}

	public static String doGet(String url, Map<String, String> map) {

		String resultString = "";
		RestTemplate client = new RestTemplate();
		HttpHeaders headers = new HttpHeaders();
		// 参数设置
		MultiValueMap<String, String> params = new LinkedMultiValueMap<String, String>();
		if (CollectionUtil.isNotEmpty(map)) {
			for (String key : map.keySet()) {
				params.add(key, map.get(key));
			}
		}

		try {

			// 设置表单提交
			headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
			HttpEntity<MultiValueMap<String, String>> requestEntity = new HttpEntity<MultiValueMap<String, String>>(
					params, headers);
			// 执行HTTP请求
			ResponseEntity<String> response = client.exchange(url, HttpMethod.GET, requestEntity, String.class);
			resultString = response.getBody();
		} catch (Exception e) {
			log.error(e.getMessage(), e);
		}

		return resultString;

	}

	public static String doPost(String url) {
		return doPost(url, null);
	}

	public static String doPost(String url, Map<String, String> map) {

		String resultString = "";
		ResponseEntity<String> response = null;
		RestTemplate client = new RestTemplate();
		HttpHeaders headers = new HttpHeaders();
		// 参数设置
		MultiValueMap<String, String> params = new LinkedMultiValueMap<String, String>();
		if (CollectionUtil.isNotEmpty(map)) {
			for (String key : map.keySet()) {
				params.add(key, map.get(key));
			}
		}

		try {

			// 请勿轻易改变此提交方式,大部分的情况下,提交方式都是表单提交
			headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
			HttpEntity<MultiValueMap<String, String>> requestEntity = new HttpEntity<MultiValueMap<String, String>>(
					params, headers);
			// 执行HTTP请求
			response = client.exchange(url, HttpMethod.POST, requestEntity, String.class);
			resultString = response.getBody();
		} catch (Exception e) {
			log.error(e.getMessage(), e);
		}
		return resultString;

	}

	public static String doPostJson(String url, String json) {

		String resultString = "";
		RestTemplate client = new RestTemplate();
		ResponseEntity<String> response = null;
		// 提交方式设置
		HttpHeaders headers = new HttpHeaders();
		headers.setContentType(MediaType.APPLICATION_JSON);
		HttpEntity<String> requestEntity = new HttpEntity<String>(json, headers);
		try {
			// 执行HTTP请求
			response = client.exchange(url, HttpMethod.POST, requestEntity, String.class);
			resultString = response.getBody();

		} catch (Exception e) {
			log.error(e.getMessage(), e);
		} finally {
			try {

			} catch (Exception e) {
				// TODO Auto-generated catch block
				log.error(e.getMessage(), e);
			}
		}
		return resultString;

	}
	
	
	/**
	 * 创建http请求头
	 * @param url
	 * @return
	 * @throws Exception
	 */
	public static URLConnection FactoryCreatURLConnection(String url) throws Exception {
		URL realUrl;
		URLConnection conn = null;
		try {
			// 打开和URL之间的连接
			realUrl = new URL(url);
			conn = realUrl.openConnection();
			conn.setRequestProperty("accept", "text/plain;charset=utf-8");
			conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=utf-8");
			conn.setRequestProperty("connection", "Keep-Alive");
			conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
		} catch (MalformedURLException e1) {
			e1.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return conn;
	}

	/**
	 * 判断连接是否可用
	 * 
	 * @param url http请求地址
	 * @return
	 */
	public static boolean isRearchUrl(String url) {
		return isRearchUrl(url, 3000);
	}

	/**
	 * 判断连接是否可用
	 * 
	 * @param url http请求地址
	 * @return
	 */
	public static boolean isRearchUrl(String url, int timeout) {

		if (StringUtils.isEmpty(url)) {
			return false;
		}
		HttpURLConnection connection = null;
		try {
			connection = (HttpURLConnection) new URL(url).openConnection();
			// 设置超时时间
			connection.setConnectTimeout(timeout);
			connection.setReadTimeout(timeout);
			if (connection.getResponseCode() >= HttpURLConnection.HTTP_OK
					&& connection.getResponseCode() <= HttpURLConnection.HTTP_VERSION) {
				return true;
			}
		} catch (Exception e) {
			log.error(" HttpURLConnection exception happend!");
			return false;
		} finally {
			if (connection != null) {
				connection.disconnect();
			}
		}
		return false;
	}

	/**
	 * 判断ip是否能ping通
	 */
	public static boolean checkIp(String ipAddr) {
		try {
			boolean status = false;
			if (!StringUtils.isEmpty(ipAddr)) {
				int timeOut = 3000; // 超时 3秒
				status = InetAddress.getByName(ipAddr).isReachable(timeOut);
				return status;
			}
			return status;
		} catch (UnknownHostException e) {
			e.printStackTrace();
			return false;
		} catch (IOException e) {
			e.printStackTrace();
			return false;
		}
	}


}
相关推荐
安然~~~4 分钟前
单例模式的理解
java·单例模式
我会冲击波12 分钟前
Easy Naming for IDEA:从命名到注释,您的编码效率助推器
java·intellij idea
池以遇13 分钟前
云原生高级---TOMCAT
java·tomcat
GalaxyPokemon14 分钟前
Linux的pthread怎么实现的?(包括到汇编层的实现)
运维·开发语言·c++
NeoFii25 分钟前
Day 39: 图像数据与显存
python·深度学习·机器学习
lsx20240627 分钟前
Ruby 条件判断
开发语言
臻实33 分钟前
Win10系统Ruby+Devkit3.4.5-1安装
开发语言·后端·ruby
IT毕设实战小研41 分钟前
Java毕业设计选题推荐 |基于SpringBoot的水产养殖管理系统 智能水产养殖监测系统 水产养殖小程序
java·开发语言·vue.js·spring boot·毕业设计·课程设计
小小深1 小时前
Spring进阶(八股篇)
java·spring boot·spring
京东云开发者1 小时前
虚引用GC耗时分析优化(由 1.2 降低至 0.1 秒)
java