目录
一、IP工具包
import java.util.HashSet;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class IpUtils {
private static final String ipv4Regex = "((25[0-5]|2[0-4]\\d|((1\\d{2})|([1-9]?\\d)))\\.){3}(25[0-5]|2[0-4]\\d|((1\\d{2})|([1-9]?\\d)))";
private static final String ipv6Regex = "((([0-9A-Fa-f]{1,4}:){7}([0-9A-Fa-f]{1,4}|:))|(([0-9A-Fa-f]{1,4}:){6}(:[0-9A-Fa-f]{1,4}|((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){5}(((:[0-9A-Fa-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){4}(((:[0-9A-Fa-f]{1,4}){1,3})|((:[0-9A-Fa-f]{1,4})?:((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){3}(((:[0-9A-Fa-f]{1,4}){1,4})|((:[0-9A-Fa-f]{1,4}){0,2}:((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){2}(((:[0-9A-Fa-f]{1,4}){1,5})|((:[0-9A-Fa-f]{1,4}){0,3}:((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){1}(((:[0-9A-Fa-f]{1,4}){1,6})|((:[0-9A-Fa-f]{1,4}){0,4}:((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3}))|:))|(:(((:[0-9A-Fa-f]{1,4}){1,7})|((:[0-9A-Fa-f]{1,4}){0,5}:((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3}))|:)))(%.+)?";
private final static String regex1="^10\\.(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|[0-9])\\.(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|[0-9])\\.(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|[0-9])$";
private final static String regex2="^172\\.(1[6789]|2[0-9]|3[01])\\.(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|[0-9])\\.(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|[0-9])$";
private final static String regex3="^192\\.168\\.(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|[0-9])\\.(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|[0-9])$";
private final static String regex4="127.0.0.0";
private final static String regex5="localhost";
private final static String regex6="0.0.0.0";
//判断给定IP是否为内网IP,暂不支持ipv6格式
public static final boolean isIntranet(String ip){
if ("".equals(ip)||ip==null) return false;
//暂不支持判断IPv6地址
if (ip.contains(":")) return false;
ip = ip.trim().toLowerCase();
if (ip.matches(regex1)||ip.matches(regex2)||ip.matches(regex3)||regex4.equals(ip)||regex5.equals(ip)||regex6.equals(ip)) return true;
else return false;
}
//判断给定字符串是否为IP
public static final boolean isNotIp(String ip){
if (ip == null || ip.isEmpty()) return false;
ip = ip.trim().toUpperCase();
if (ip.contains(":") && ip.matches(ipv6Regex)) {
return true;
}else if (ip.contains(".") && ip.matches(ipv4Regex)) {
return true;
}else return false;
}
//在给定的字符串中提取IP。
public static final Set<String> extractIp(String s){
HashSet<String> ips = new HashSet<>();
if (s == null || s.isEmpty()) return ips;
s = s.trim();
Matcher ipv4 = Pattern.compile(ipv4Regex).matcher(s);
Matcher ipv6 = Pattern.compile(ipv6Regex).matcher(s);
while (ipv4.find()) {
ips.add(ipv4.group());
}
while (ipv6.find()) {
ips.add(ipv6.group());
}
return ips;
}
//判断给定的字符串是否包含IP
public static final boolean isIncludeIp(String s){
if (null == s||s.isEmpty()) return false;
if (s.contains(".") || !s.contains(":")){
if (Pattern.compile(ipv4Regex).matcher(s).find()) return true;
else if (Pattern.compile(ipv6Regex).matcher(s).find()) return true;
else return false;
}else return false;
}
}
二、时间工具包
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
public class DateUtils {
public static final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
/**
* 获取当前日期
* */
public static String nowDataTime(){
return dateFormat.format(new Date(System.currentTimeMillis()));
}
/**
* 时间格式为yyyy-MM-dd HH:mm:ss
* 指定时间计算前一天返回
* */
public static String oneDayAgo(String s){
if ("".equals(s)||s==null) return "";
Date parse = null;
try {
parse = dateFormat.parse(s);
} catch (ParseException e) {
return "";
}
Calendar calendar = Calendar.getInstance();
calendar.setTime(parse);
calendar.add(Calendar.DAY_OF_MONTH,-1);
Date time = calendar.getTime();
return dateFormat.format(time);
}
/**
* 时间格式为yyyy-MM-dd HH:mm:ss
* 指定时间计算后一天返回
* */
public static String oneDayLater(String s){
if ("".equals(s)||s==null) return "";
Date parse = null;
try {
parse = dateFormat.parse(s);
} catch (ParseException e) {
return "";
}
Calendar calendar = Calendar.getInstance();
calendar.setTime(parse);
calendar.add(Calendar.DAY_OF_MONTH,1);
Date time = calendar.getTime();
return dateFormat.format(time);
}
/**
* 时间格式为yyyy-MM-dd HH:mm:ss
* 指定时间计算 指定天数(例如 1 或者 -1) 返回
* */
public static String Day(String s,Integer num){
if ("".equals(s)||s==null) return "";
Date parse = null;
try {
parse = dateFormat.parse(s);
} catch (ParseException e) {
return "";
}
Calendar calendar = Calendar.getInstance();
calendar.setTime(parse);
calendar.add(Calendar.DAY_OF_MONTH,num);
Date time = calendar.getTime();
return dateFormat.format(time);
}
}
三、域名工具包
import org.springframework.stereotype.Component;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
@Component
public class DomainUtils {
private final static Set<String> PublicSuffixSet = new HashSet<>(
Arrays.asList(new String("com|org|net|gov|edu|co|tv|mobi|info|asia|xxx|onion|cn|com.cn|edu.cn|gov.cn|net.cn|org.cn|jp|kr|tw|com.hk|hk|com.hk|org.hk|se|com.se|org.se|pk|edu.pk")
.split("\\|")));
private static Pattern IP_PATTERN = Pattern.compile("(\\d{1,3}\\.){3}(\\d{1,3})");
/**
* 获取url的顶级域名
*
* @param url
* @return
*/
public static String getDomainName(URL url) {
String host = url.getHost();
if (host.endsWith(".")) {
host = host.substring(0, host.length() - 1);
}
if (IP_PATTERN.matcher(host).matches()) {
return host;
}
int index = 0;
String candidate = host;
for (; index >= 0; ) {
index = candidate.indexOf('.');
String subCandidate = candidate.substring(index + 1);
if (PublicSuffixSet.contains(subCandidate)) {
return candidate;
}
candidate = subCandidate;
}
return candidate;
}
/**
* 获取url的顶级域名
*
* @param url
* @return
* @throws MalformedURLException
*/
public static String getDomainName(String url) throws MalformedURLException {
return getDomainName(new URL(url));
}
/**
* 判断两个url顶级域名是否相等
*
* @param url1
* @param url2
* @return
*/
public static boolean isSameDomainName(URL url1, URL url2) {
return getDomainName(url1).equalsIgnoreCase(getDomainName(url2));
}
/**
* 判断两个url顶级域名是否相等
*
* @param url1
* @param url2
* @return
* @throws MalformedURLException
*/
public static boolean isSameDomainName(String url1, String url2) throws MalformedURLException {
return isSameDomainName(new URL(url1), new URL(url2));
}
/**
* 获取根域名
* @param domainsName
* @return
* @throws MalformedURLException
*/
public static List<String> getRootDomainName(List<String> domainsName) throws MalformedURLException {
List<String> domainlist = new ArrayList<>();
for (String domainName : domainsName) {
String s = "http://" + domainName;
String domainName1 = DomainUtils.getDomainName(s);
if (!domainlist.contains(domainName1)) {
domainlist.add(domainName1);
}
}
return domainlist;
}
/**
* 获取根域名
* @param domainName
* @return
* @throws MalformedURLException
*/
public static String getRootDomainNameByOne(String domainName) throws MalformedURLException {
String s = "http://" + domainName;
String domain = DomainUtils.getDomainName(s);
return domain;
}
/**
* 判断是否为域名
* @param domain
* @return
*/
public static boolean isDomian(String domain) {
String pattern = "[a-zA-Z0-9][-a-zA-Z0-9]{0,62}(\\.[a-zA-Z0-9][-a-zA-Z0-9]{0,62})+\\.?";
Pattern r = Pattern.compile(pattern);
Matcher m = r.matcher(domain);
return m.matches();
}
}
四、http请求工具包
import org.apache.http.*;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.*;
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 org.springframework.util.StringUtils;
import javax.xml.bind.DatatypeConverter;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* http请求工具类
*
* @author Clover
*
*/
public class HttpClientUtil {
/**
* 获取请求的url链接的值
*
* @return
*/
public static String get(String username, String password, String url) {
CloseableHttpClient client = HttpClients.createDefault();
RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(2000).setConnectionRequestTimeout(1000)
.setSocketTimeout(30000).build();
HttpGet httpGet = new HttpGet(url);
httpGet.setConfig(requestConfig);
String encoding = null;
try {
encoding = DatatypeConverter.printBase64Binary((username + ":" + password).getBytes("UTF-8"));
} catch (UnsupportedEncodingException e1) {
e1.printStackTrace();
}
httpGet.setHeader("Authorization", "Basic " + encoding);
CloseableHttpResponse response = null;
try {
response = client.execute(httpGet);
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
if (statusCode == HttpStatus.SC_OK) {
String charset = getContentCharset(response);
if (StringUtils.isEmpty(charset)) {
charset = "utf-8";
}
return EntityUtils.toString(response.getEntity(), charset);
}
} catch (ClientProtocolException e) {
System.out.println("Http协议出现问题:" + e.getMessage());
e.printStackTrace();
} catch (ParseException e) {
System.out.println("解析错误:" + e.getMessage());
e.printStackTrace();
} catch (IOException e) {
System.out.println("IO异常:" + e.getMessage());
e.printStackTrace();
} finally {
if (response != null) {
try {
response.close();
client.close();
} catch (IOException e) {
System.out.println("HttpClientUtil释放连接出错:" + e.getMessage());
e.printStackTrace();
}
}
}
return null;
}
public static String post(String username, String password, String url, Map<String, Object> paramsMap) {
CloseableHttpClient client = HttpClients.createDefault();
RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(2000).setConnectionRequestTimeout(1000)
.setSocketTimeout(2000).build();
HttpPost httpPost = new HttpPost(url);
httpPost.setConfig(requestConfig);
String encoding = null;
try {
encoding = DatatypeConverter.printBase64Binary((username + ":" + password).getBytes("UTF-8"));
} catch (UnsupportedEncodingException e1) {
e1.printStackTrace();
}
httpPost.setHeader("Authorization", "Basic " + encoding);
List<NameValuePair> list = new ArrayList<NameValuePair>();
for (Map.Entry<String, Object> entry : paramsMap.entrySet()) {
list.add(new BasicNameValuePair(entry.getKey(), String.valueOf(entry.getValue())));
}
CloseableHttpResponse response = null;
try {
httpPost.setEntity(new UrlEncodedFormEntity(list, "UTF-8"));
response = client.execute(httpPost);
if (response != null) {
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode == HttpStatus.SC_OK) {
return EntityUtils.toString(response.getEntity());
} else {
HttpEntity resEntity = response.getEntity();
if (resEntity != null) {
String error = EntityUtils.toString(resEntity, "UTF-8");
System.out.println("Http错误:" + error);
System.out.println(error);
}
}
}
} catch (ClientProtocolException e) {
System.out.println("Http协议出现问题:" + e.getMessage());
e.printStackTrace();
} catch (ParseException e) {
System.out.println("解析错误:" + e.getMessage());
e.printStackTrace();
} catch (IOException e) {
System.out.println("IO异常:" + e.getMessage());
e.printStackTrace();
} finally {
if (response != null) {
try {
response.close();
client.close();
} catch (IOException e) {
System.out.println("HttpClientUtil释放连接出错:" + e.getMessage());
e.printStackTrace();
}
}
}
return null;
}
/** post **/
public static String post(String username, String password, String url) {
CloseableHttpClient client = HttpClients.createDefault();
RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(2000).setConnectionRequestTimeout(1000)
.setSocketTimeout(2000).build();
HttpPost httpdel = new HttpPost(url);
httpdel.setConfig(requestConfig);
String encoding = null;
try {
encoding = DatatypeConverter.printBase64Binary((username + ":" + password).getBytes("UTF-8"));
} catch (UnsupportedEncodingException e1) {
e1.printStackTrace();
}
httpdel.setHeader("Authorization", "Basic " + encoding);
CloseableHttpResponse response = null;
try {
response = client.execute(httpdel);
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
if (statusCode == HttpStatus.SC_OK) {
String charset = getContentCharset(response);
if (StringUtils.isEmpty(charset)) {
charset = "utf-8";
}
return EntityUtils.toString(response.getEntity(), charset);
}
} catch (ClientProtocolException e) {
System.out.println("Http协议出现问题:" + e.getMessage());
e.printStackTrace();
} catch (ParseException e) {
System.out.println("解析错误:" + e.getMessage());
e.printStackTrace();
} catch (IOException e) {
System.out.println("IO异常:" + e.getMessage());
e.printStackTrace();
} finally {
if (response != null) {
try {
response.close();
client.close();
} catch (IOException e) {
System.out.println("HttpClientUtil释放连接出错:" + e.getMessage());
e.printStackTrace();
}
}
}
return null;
}
public static String post(String username, String password, String url, String paramsJson,
Map<String, String> headerMap) {
CloseableHttpClient client = HttpClients.createDefault();
RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(2000).setConnectionRequestTimeout(1000)
.setSocketTimeout(2000).build();
HttpPost httpPost = new HttpPost(url);
httpPost.setConfig(requestConfig);
String encoding = null;
try {
encoding = DatatypeConverter.printBase64Binary((username + ":" + password).getBytes("UTF-8"));
} catch (UnsupportedEncodingException e1) {
e1.printStackTrace();
}
httpPost.setHeader("Authorization", "Basic " + encoding);
for (Map.Entry<String, String> entry : headerMap.entrySet()) {
httpPost.addHeader(entry.getKey(), entry.getValue());
}
CloseableHttpResponse response = null;
try {
StringEntity entity = new StringEntity(paramsJson, Charset.forName("UTF-8"));
entity.setContentEncoding("UTF-8");
// 发送Json格式的数据请求
entity.setContentType("application/json");
httpPost.setEntity(entity);
response = client.execute(httpPost);
if (response != null) {
HttpEntity resEntity = response.getEntity();
if (resEntity != null) {
String result = EntityUtils.toString(resEntity, "UTF-8");
System.out.println("Http错误:" + result);
return result;
}
// int statusCode = response.getStatusLine().getStatusCode();
}
} catch (ClientProtocolException e) {
System.out.println("Http协议出现问题:" + e.getMessage());
e.printStackTrace();
} catch (ParseException e) {
System.out.println("解析错误:" + e.getMessage());
e.printStackTrace();
} catch (IOException e) {
System.out.println("IO异常:" + e.getMessage());
e.printStackTrace();
} finally {
if (response != null) {
try {
response.close();
client.close();
} catch (IOException e) {
System.out.println("HttpClientUtil释放连接出错:" + e.getMessage());
e.printStackTrace();
}
}
}
return null;
}
// 构建唯一会话Id
public static String getSessionId() {
String str = UUID.randomUUID().toString();
return str.substring(0, 8) + str.substring(9, 13) + str.substring(14, 18) + str.substring(19, 23)
+ str.substring(24);
}
public static String put(String username, String password, String url) {
CloseableHttpClient client = HttpClients.createDefault();
RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(2000).setConnectionRequestTimeout(1000)
.setSocketTimeout(2000).build();
HttpPut httpPut = new HttpPut(url);
httpPut.setConfig(requestConfig);
String encoding = null;
try {
encoding = DatatypeConverter.printBase64Binary((username + ":" + password).getBytes("UTF-8"));
} catch (UnsupportedEncodingException e1) {
e1.printStackTrace();
}
httpPut.setHeader("Authorization", "Basic " + encoding);
CloseableHttpResponse response = null;
try {
response = client.execute(httpPut);
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
if (statusCode == HttpStatus.SC_OK) {
String charset = getContentCharset(response);
if (StringUtils.isEmpty(charset)) {
charset = "utf-8";
}
return EntityUtils.toString(response.getEntity(), charset);
}
} catch (ClientProtocolException e) {
System.out.println("Http协议出现问题:" + e.getMessage());
e.printStackTrace();
} catch (ParseException e) {
System.out.println("解析错误:" + e.getMessage());
e.printStackTrace();
} catch (IOException e) {
System.out.println("IO异常:" + e.getMessage());
e.printStackTrace();
} finally {
if (response != null) {
try {
response.close();
client.close();
} catch (IOException e) {
System.out.println("HttpClientUtil释放连接出错:" + e.getMessage());
e.printStackTrace();
}
}
}
return null;
}
public static String head(String username, String password, String url) {
CloseableHttpClient client = HttpClients.createDefault();
RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(2000).setConnectionRequestTimeout(1000)
.setSocketTimeout(2000).build();
HttpHead httpHead = new HttpHead(url);
httpHead.setConfig(requestConfig);
String encoding = null;
try {
encoding = DatatypeConverter.printBase64Binary((username + ":" + password).getBytes("UTF-8"));
} catch (UnsupportedEncodingException e1) {
e1.printStackTrace();
}
httpHead.setHeader("Authorization", "Basic " + encoding);
CloseableHttpResponse response = null;
try {
response = client.execute(httpHead);
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
if (statusCode == HttpStatus.SC_OK) {
String charset = getContentCharset(response);
if (StringUtils.isEmpty(charset)) {
charset = "utf-8";
}
return EntityUtils.toString(response.getEntity(), charset);
}
} catch (ClientProtocolException e) {
System.out.println("Http协议出现问题:" + e.getMessage());
e.printStackTrace();
} catch (ParseException e) {
System.out.println("解析错误:" + e.getMessage());
e.printStackTrace();
} catch (IOException e) {
System.out.println("IO异常:" + e.getMessage());
e.printStackTrace();
} finally {
if (response != null) {
try {
response.close();
client.close();
} catch (IOException e) {
System.out.println("HttpClientUtil释放连接出错:" + e.getMessage());
e.printStackTrace();
}
}
}
return null;
}
public static String delete(String username, String password, String url) {
CloseableHttpClient client = HttpClients.createDefault();
RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(2000).setConnectionRequestTimeout(1000)
.setSocketTimeout(2000).build();
HttpDelete httpDelete = new HttpDelete(url);
httpDelete.setConfig(requestConfig);
String encoding = null;
try {
encoding = DatatypeConverter.printBase64Binary((username + ":" + password).getBytes("UTF-8"));
} catch (UnsupportedEncodingException e1) {
e1.printStackTrace();
}
httpDelete.setHeader("Authorization", "Basic " + encoding);
CloseableHttpResponse response = null;
try {
response = client.execute(httpDelete);
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
if (statusCode == HttpStatus.SC_OK) {
String charset = getContentCharset(response);
if (StringUtils.isEmpty(charset)) {
charset = "utf-8";
}
return EntityUtils.toString(response.getEntity(), charset);
}
} catch (ClientProtocolException e) {
System.out.println("Http协议出现问题:" + e.getMessage());
e.printStackTrace();
} catch (ParseException e) {
System.out.println("解析错误:" + e.getMessage());
e.printStackTrace();
} catch (IOException e) {
System.out.println("IO异常:" + e.getMessage());
e.printStackTrace();
} finally {
if (response != null) {
try {
response.close();
client.close();
} catch (IOException e) {
System.out.println("HttpClientUtil释放连接出错:" + e.getMessage());
e.printStackTrace();
}
}
}
return null;
}
/**
* 获取请求编码
*
* @param response
* @return 编码
*/
private static String getContentCharset(HttpResponse response) {
String charset = "";
try {
Header header = response.getEntity().getContentType();
if (header != null) {
String value = header.getValue();
Pattern p = Pattern.compile("charset=(.+)");
Matcher m = p.matcher(value);
if (m.find()) {
String group = m.group(1);
if (!StringUtils.isEmpty(group)) {
charset = group.trim();
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return charset;
}
}