Java工具包整理

目录

一、IP工具包

 二、时间工具包

 三、域名工具包

 四、http请求工具包


一、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;
	}
}

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
此工具我不再更新,里面大多数方法我迁移到了hutool工具包中,而其中一些不常用的功能被遗弃,项目暂留做为以后参考。 common-tools 一、数据库工具类 1、com.baijob.commonTools.db.ds C3p0Ds 和 DruidDs分别是两种连接池的实现,依赖于数据库配置文件,配置文件的样例参考config/db-example.setting 使用时将db-example.setting复制于${classpath}/config/db.setting,按照配置文件中的说明替换相应值 如果使用Druid,则需参考druid-example.setting创建${classpath}/config/druid.setting文件,详情请参考官方文档 使用C3P0则需要参考c3p0-config-example.xml创建${classpath}/c3p0-config.xml来调节C3P0参数 此时即可调用C3p0Ds.getDataSource()或DruidDs.getDataSource()方法获得默认的数据源 如果要自定义数据库配置文件的参数,请调用相应的init(),传入相关参数 注:Setting对象请参考与之对应的章节 2、com.baijob.commonTools.db.DbUtil 数据库工具类,提供了关闭方法:关闭可以传入多个参数,关闭的顺序是按照参数的顺序来的,用于一次性关闭Connnection、Statement、ResultSet等 newSqlRunner方法用于快速新建一个SqlRunner(此类介绍参考下问) 3、com.baijob.commonTools.db.DsSetting,用于读取db.setting文件辅助类,内部使用 4、com.baijob.commonTools.db.SqlRunner类参考Apache的DbUtils工具包,封装了常用的增删改查方法,与com.baijob.commonTools.db.RsHandler配合使用 com.baijob.commonTools.db.RsHandler接口与Apache的DbUtils的ResultSetHandler等价,抽象结果集处理。 二、邮件工具类 1、com.baijob.commonTools.mail.MailAccount 邮件账户类。 可以调用MailAccount(String accountSettingFileBaseClassLoader)读取相对路径的Setting文件,配置参考mailAccount-example.setting 2、com.baijob.commonTools.mail.MailUtil邮件发送工具类,方法请参考注释 此工具类依赖javax.mail,请参考pom.xml添加依赖或手动下载 三、网络相关工具类 1、com.baijob.commonTools.net.AccessControl访问控制,基于配置文件,可以设定IP白名单或黑名单,可以通过配置文件实现简单的账户验证。 配置文件请参考access-example.xml 2、com.baijob.commonTools.net.Connector 连接对象实体类,有host、端口、用户名、密码等属性 3、com.baijob.commonTools.net.HtmlUtil HTML工具类,暂时只提供特殊字符转义 4、com.baijob.commonTools.net.SocketUtil socket工具类。 isUsableLocalPort() 检测本地某个端口是否可用(可用是指没有被其他程序占用) isValidPort()是否是符合规范的端口号 longToIpv4()将long转换为ipv4地址,反方法是ipv4ToLong() netCat()简易的数据发送方法 5、com.baijob.commonTools.net.SSHUtil SSH相关工具类 getSession()获得一个SSH会话 bindPort()将远程主机的端口映射到本地某个端口 6、com.baijob.commonTools.net.URLUtil 将相对、绝对路径转换为URL对象,用于网络或文件流的读写,Setting的配置依赖此工具包 四、线程相关工具类 1、com.baijob.commonTools.thread.BaseRunnable 此类实现了Runnable接口,扩展了功能。 增加名称、ID,调用次数和时间统计、线程停止接口等,并且在线程运行时,不允许此线程第二次启动。 2、com.baijob.commonTools.thread.Executor 线程池工具类 调用静态方法execute()启动线程,此线程在公共的线程池中执行 若想自定义线程池大小或独立控制,可调用newExecutor()实例化一个线程池 excAsync()执行一个异步方法 3、com.baijob.commonTools.thread.SyncQueue 阻塞队列,简化了JDK的BlockingQueue
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值