CookieUtil 可设置cookie有效期,增加读取cookie
package cn.ways.gtids.common.utils;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* @ClassName:CookieUtil
* @Description: Cookie处理Util类
* @author Zhaohy
* @Modifier:
* @Modify Date:
* @Modify Note:
* @version
*/
public class CookieUtil {
/**
* @Title: addCookie
* @Description:
* @param response
* @param name 名称
* @param value 值
* @param maxAge 最长时间 单位秒
* @throws
*/
public static void addCookie(HttpServletResponse response, String name, String value, int maxAge) {
Cookie cookie = new Cookie(name, value);
cookie.setPath("/");
if (maxAge>0) cookie.setMaxAge(maxAge);
response.addCookie(cookie);
}
/**
* @Title: addCookie
* @Description:
* @param response
* @param name cookie名称
* @param path cookie存放路径
* @param value cookie值
* @param maxAge cookie最长时间
* @throws
*/
public static void addCookie(HttpServletResponse response, String name,String path, String value, int maxAge) {
Cookie cookie = new Cookie(name, value);
cookie.setPath(path);
if (maxAge>0) cookie.setMaxAge(maxAge);
response.addCookie(cookie);
}
/**
* @Title: getCookieByName
* @Description: 获取cookie的值
* @param request
* @param name 名称
* @return
* @throws
*/
public static String getCookieByName(HttpServletRequest request, String name) {
Map<String, Cookie> cookieMap = CookieUtil.readCookieMap(request);
if(cookieMap.containsKey(name)){
Cookie cookie = (Cookie)cookieMap.get(name);
return cookie.getValue();
}else{
return null;
}
}
protected static Map<String, Cookie> readCookieMap(HttpServletRequest request) {
Map<String, Cookie> cookieMap = new HashMap<String, Cookie>();
Cookie[] cookies = request.getCookies();
if (null != cookies) {
for (int i = 0; i < cookies.length; i++) {
cookieMap.put(cookies[i].getName(), cookies[i]);
}
}
return cookieMap;
}
}
DateTimeUtil 日期处理
package cn.ways.gtids.common.utils;
import java.sql.Timestamp;
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;
import java.util.Locale;
import java.util.SimpleTimeZone;
import java.util.TimeZone;
/**
* 日期处理类
*/
public class DateTimeUtil {
public static String SHORT_FORM = "yyyy-MM-dd";
public static String LONG_FORM = "yyyy-MM-dd HH:mm:ss";
// ------------------------------------------------------------------------------
/**
* 检查日期是否满足"yyyy-MM-dd"的格式,且toDate不小于fromDate
*
* @param fromDate
* 开始日期
* @param toDate
* 结束日期
* @param dates
* 用于返回处理后的开始,结束日期
* @return 日期格式正确,返回true,否则false
*/
public static boolean isValidDates(String fromDate, String toDate,
String[] dates) {
if (fromDate == null || fromDate.trim().length() == 0)
return false;
if (toDate == null || toDate.trim().length() == 0)
return false;
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
Date begin = null;
Date end = null;
try {
begin = format.parse(fromDate);
end = format.parse(toDate);
if (begin.after(end))
return false;
dates[0] = format.format(begin);
dates[1] = format.format(end);
} catch (Exception e) {
return false;
}
return true;
}
public static Integer[] genBetwwenYears(Integer syear, Integer eyear) {
if(syear == null || eyear == null) return null;
int index = eyear - syear;
if(index < 0) return null;
Integer[] datas = null;
if(index == 0) {
return new Integer[]{syear};
} else {
datas = new Integer[index+1];
datas[0] = syear;
for (int i = 1; i < index+1; i++) {
datas[i] = syear+i;
}
}
return datas;
}
/**
* @author zgk
* @Title: format
* @Description: Date 转 String
* @param time
* @param formaterKey
* @return
* @throws
*/
public static String format(Date time, String formaterKey) {
String date = "";
if (formaterKey != null) {
if (time == null) {
date = "";
} else {
SimpleDateFormat formater = new SimpleDateFormat(formaterKey);
date = formater.format(time);
}
return date;
}
throw new IllegalArgumentException(new StringBuilder("格式化串存在问题")
.append(formaterKey).toString());
}
/**
* @Title: getMonthEnDesc
* @Description: 获取月份英文简写描述
* @param month
* @return
* @throws
*/
public static String getMonthEnSortDesc(Date month) {
if(month == null) return "";
Calendar c = Calendar.getInstance();
c.setTime(month);
int m = c.get(Calendar.MONTH) + 1;
switch (m) {
case 1: return "Jan";
case 2: return "Feb";
case 3: return "Mar";
case 4: return "Apr";
case 5: return "May";
case 6: return "Jun";
case 7: return "Jul";
case 8: return "Aug";
case 9: return "Sep";
case 10: return "Oct";
case 11: return "Nov";
case 12: return "Dec";
}
return "";
}
/**
* 数字月份转换成英文简写月份
* @param month
* @return
*/
public static String getMonthEnSortDesc(int month) {
switch (month) {
case 1: return "Jan";
case 2: return "Feb";
case 3: return "Mar";
case 4: return "Apr";
case 5: return "May";
case 6: return "Jun";
case 7: return "Jul";
case 8: return "Aug";
case 9: return "Sep";
case 10: return "Oct";
case 11: return "Nov";
case 12: return "Dec";
}
return "";
}
/**
* 数字月份转换成英文简写月份
* @param month
* @return
*/
public static int convertMonthToNumber(String month) {
int num = 0;
if(month==null||month.trim().equals("")){
num = 0;
}else{
if(month.equals("Jan")){
num = 1;
}else if(month.equals("Feb")){
num = 2;
}else if(month.equals("Mar")){
num = 3;
}else if(month.equals("Apr")){
num = 4;
}else if(month.equals("May")){
num = 5;
}else if(month.equals("Jun")){
num = 6;
}else if(month.equals("Jul")){
num = 7;
}else if(month.equals("Aug")){
num = 8;
}else if(month.equals("Sep")){
num = 9;
}else if(month.equals("Oct")){
num = 10;
}else if(month.equals("Nov")){
num = 11;
}else if(month.equals("Dec")){
num = 12;
}
}
return num;
}
/**
* @Title: getBeginOfHour
* @Description: 获取某小时开始时间 如:2013-05-09 06:00:00
* @param time
* @return
* @throws
*/
public static Date getBeginOfHour(Date time) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(time);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MILLISECOND, 0);
return calendar.getTime();
}
/**
* @Title: getEndOfHour
* @Description: 获取小时结束时间 如:2013-05-09 06:59:59
* @param time
* @return
* @throws
*/
public static Date getEndOfHour(Date time) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(time);
calendar.set(Calendar.MINUTE, 59);
calendar.set(Calendar.SECOND, 59);
calendar.set(Calendar.MILLISECOND, 0);
return calendar.getTime();
}
/**
* @Title: getBeginOfDay
* @Description: 获取某日开始时间 如:2013-05-09 00:00:00
* @param time
* @return
* @throws
*/
public static Date getBeginOfDay(Date time) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(time);
calendar.set(Calendar.HOUR_OF_DAY, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MILLISECOND, 0);
return calendar.getTime();
}
/**
* @Title: getEndOfDay
* @Description: 获取某日结束时间 如:2013-05-09 59:59:59
* @param time
* @return
* @throws
*/
public static Date getEndOfDay(Date time) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(time);
calendar.set(Calendar.HOUR_OF_DAY, 23);
calendar.set(Calendar.MINUTE, 59);
calendar.set(Calendar.SECOND, 59);
calendar.set(Calendar.MILLISECOND, 0);
return calendar.getTime();
}
/**
* @Title: getBeginOfMonth
* @Description: 获取月开始时间
* @param time
* @return yyyy-MM-dd 00:00:00 000
* @throws
*/
public static Date getBeginOfMonth(Date time) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(time);
calendar.set(Calendar.DATE, 1);
calendar.set(Calendar.HOUR_OF_DAY, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MILLISECOND, 0);
return calendar.getTime();
}
/**
* @Title: getEndOfMonth
* @Description: 获取月结束时间
* @param time
* @return yyyy-MM-dd 23:59:59 999
*/
public static Date getEndOfMonth(Date time) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(time);
calendar.set(Calendar.DATE, 1);
calendar.set(Calendar.HOUR_OF_DAY, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MILLISECOND, 0);
calendar.add(Calendar.MONTH, 1);
calendar.add(Calendar.MILLISECOND, -1);
return calendar.getTime();
}
/**
* @Title: getBeginOfYear
* @Description: 获取开始结束时间
* @param date
* @return yyyy-MM-dd 00:00:00 000
*/
public static Date getBeginOfYear(Date date) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.set(Calendar.MONTH, 0);
calendar.set(Calendar.DAY_OF_MONTH, 1);
calendar.set(Calendar.HOUR_OF_DAY, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MILLISECOND, 0);
return calendar.getTime();
}
/**
* @Title: getBeginOfQuarter
* @Description: 获取季度的开始时间,即2012-01-1 00:00:00
* @param date
* @return
* @throws
*/
public static Date getBeginOfQuarter(Date date) {
Calendar c = Calendar.getInstance();
c.setTime(date);
int currentMonth = c.get(Calendar.MONTH) + 1;
try {
if (currentMonth >= 1 && currentMonth <= 3)
c.set(Calendar.MONTH, 0);
else if (currentMonth >= 4 && currentMonth <= 6)
c.set(Calendar.MONTH, 3);
else if (currentMonth >= 7 && currentMonth <= 9)
c.set(Calendar.MONTH, 6);
else if (currentMonth >= 10 && currentMonth <= 12)
c.set(Calendar.MONTH, 9);
c.set(Calendar.DATE, 1);
c.set(Calendar.HOUR_OF_DAY, 0);
c.set(Calendar.MINUTE, 0);
c.set(Calendar.SECOND, 0);
c.set(Calendar.MILLISECOND, 0);
} catch (Exception e) {
e.printStackTrace();
}
return c.getTime();
}
/**
* @Title: getEndOfQuarter
* @Description: 获取季度的结束时间,即2012-03-31 23:59:59
* @param date
* @return
* @throws
*/
public static Date getEndOfQuarter(Date date) {
Calendar c = Calendar.getInstance();
c.setTime(date);
int currentMonth = c.get(Calendar.MONTH) + 1;
try {
if (currentMonth >= 1 && currentMonth <= 3) {
c.set(Calendar.MONTH, 2);
c.set(Calendar.DATE, 31);
} else if (currentMonth >= 4 && currentMonth <= 6) {
c.set(Calendar.MONTH, 5);
c.set(Calendar.DATE, 30);
} else if (currentMonth >= 7 && currentMonth <= 9) {
c.set(Calendar.MONTH, 8);
c.set(Calendar.DATE, 30);
} else if (currentMonth >= 10 && currentMonth <= 12) {
c.set(Calendar.MONTH, 11);
c.set(Calendar.DATE, 31);
}
c.set(Calendar.HOUR_OF_DAY, 23);
c.set(Calendar.MINUTE, 59);
c.set(Calendar.SECOND, 59);
c.set(Calendar.MILLISECOND, 0);
} catch (Exception e) {
e.printStackTrace();
}
return c.getTime();
}
/**
* @Title: getQuarterStrDesc
* @Description: 获取季度的中文描述 如:2013-01-01 13Q1
* @param date
* @return
* @throws
*/
public static String getQuarterStrDesc(Date date) {
Calendar c = Calendar.getInstance();
c.setTime(date);
int currentMonth = c.get(Calendar.MONTH) + 1;
String desc = "";
try {
if (currentMonth >= 1 && currentMonth <= 3)
desc = format(date, "yy") + "Q1";
else if (currentMonth >= 4 && currentMonth <= 6)
desc = format(date, "yy") + "Q2";
else if (currentMonth >= 7 && currentMonth <= 9)
desc = format(date, "yy") + "Q3";
else if (currentMonth >= 10 && currentMonth <= 12)
desc = format(date, "yy") + "Q4";
} catch (Exception e) {
e.printStackTrace();
}
return desc;
}
/**
* @Title: getEndOfYear
* @Description: 获取年结束时间
* @param time
* @return yyyy-MM-dd 23:59:59 999
*/
public static Date getEndOfYear(Date date) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.set(Calendar.MONTH, 12);
calendar.set(Calendar.DAY_OF_MONTH, 0);
calendar.set(Calendar.HOUR_OF_DAY, 23);
calendar.set(Calendar.MINUTE, 59);
calendar.set(Calendar.SECOND, 59);
calendar.set(Calendar.MILLISECOND, 0);
return calendar.getTime();
}
/**
* 取得指定日期所在周的第一天
* @param time
* @return yyyy-MM-dd 00:00:00 000
*/
public static Date getBeginOfWeek(Date time){
Calendar calendar = Calendar.getInstance();
calendar.setTime(time);
calendar.setFirstDayOfWeek(Calendar.MONDAY);
calendar.set(Calendar.HOUR_OF_DAY, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MILLISECOND, 0);
calendar.set(Calendar.DAY_OF_WEEK, calendar.getFirstDayOfWeek());
return calendar.getTime();
}
/**
* 取得指定日期所在周的最后一天
* @param time
* @return yyyy-MM-dd 23:59:59 999
*/
public static Date getEndOfWeek(Date time){
Calendar calendar = Calendar.getInstance();
calendar.setTime(time);
calendar.setFirstDayOfWeek(Calendar.MONDAY);
calendar.set(Calendar.HOUR_OF_DAY, 23);
calendar.set(Calendar.MINUTE, 59);
calendar.set(Calendar.SECOND, 59);
calendar.set(Calendar.MILLISECOND, 0);
calendar.set(Calendar.DAY_OF_WEEK, calendar.getFirstDayOfWeek()+6);
return calendar.getTime();
}
/**
* 判断指定日期,是否为周末
* @param time
* @return boolean
*/
public static boolean isSunday(Date time){
boolean isWeather = false;
Calendar calendar = Calendar.getInstance();
calendar.setTime(time);
int w = calendar.get(Calendar.DAY_OF_WEEK);
if(w == 1 || w == 7){
isWeather = true;
}
return isWeather;
}
/**
* 对<code>Date</code>型的数据进行加减操作
* @param date 日期
* @param amount 步长
* @param field 针对的字段
* @return
*/
public static Date add(Date date, int amount, int field) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.add(field, amount);
return calendar.getTime();
}
/**
* @Title: getNow
* @Description:
* @return
* @throws
*/
public static Date getNow() {
return new Date(System.currentTimeMillis());
}
/**
* 判断时间大于或者等于当天
*
* @param day
* 时间
* @return
*/
public static boolean isGreaterOrEquToday(Date day) {
java.util.Calendar tc = Calendar.getInstance();
tc.setTime(day);
Calendar td = Calendar.getInstance();
td.set(Calendar.HOUR_OF_DAY, 0);
td.set(Calendar.MINUTE, 0);
td.set(Calendar.SECOND, 0);
td.set(Calendar.MILLISECOND, 0);
return tc.after(td) || tc.equals(td);
}
/**
* @Title: isSameDay
* @Description: 判断两个日期是否相等
* @param day1
* @param day2
* @return
* @throws
*/
public static boolean isSameDay(Date day1, Date day2) {
java.util.Calendar tc = Calendar.getInstance();
tc.setTime(day1);
tc.set(Calendar.HOUR_OF_DAY, 0);
tc.set(Calendar.MINUTE, 0);
tc.set(Calendar.SECOND, 0);
tc.set(Calendar.MILLISECOND, 0);
Calendar td = Calendar.getInstance();
td.setTime(day2);
td.set(Calendar.HOUR_OF_DAY, 0);
td.set(Calendar.MINUTE, 0);
td.set(Calendar.SECOND, 0);
td.set(Calendar.MILLISECOND, 0);
return tc.equals(td);
}
/**
* 判断时间小于或者等于当天
*
* @param day
* 时间
* @return
*/
public static boolean isLessOrEquToday(Date day) {
java.util.Calendar tc = Calendar.getInstance();
tc.setTime(day);
Calendar td = Calendar.getInstance();
td.set(Calendar.HOUR_OF_DAY, 0);
td.set(Calendar.MINUTE, 0);
td.set(Calendar.SECOND, 0);
td.set(Calendar.MILLISECOND, 0);
return tc.before(td) || tc.equals(td);
}
/**
* 判断时间大于或者等于当月
*
* @param day
* 时间
* @return
*/
public static boolean isGreaterOrEquThisMonth(Date day) {
java.util.Calendar tc = Calendar.getInstance();
tc.setTime(day);
tc.set(Calendar.DAY_OF_MONTH, 1);
tc.set(Calendar.HOUR_OF_DAY, 0);
tc.set(Calendar.MINUTE, 0);
tc.set(Calendar.SECOND, 0);
tc.set(Calendar.MILLISECOND, 0);
Calendar td = Calendar.getInstance();
td.set(Calendar.DAY_OF_MONTH, 1);
td.set(Calendar.HOUR_OF_DAY, 0);
td.set(Calendar.MINUTE, 0);
td.set(Calendar.SECOND, 0);
td.set(Calendar.MILLISECOND, 0);
return tc.after(td) || tc.equals(td);
}
/**
* 判断时间是否是当月
* @param day
* @return
*/
public static boolean isThisMonth(Date day) {
java.util.Calendar tc = Calendar.getInstance();
tc.setTime(day);
tc.set(Calendar.DAY_OF_MONTH, 1);
tc.set(Calendar.HOUR_OF_DAY, 0);
tc.set(Calendar.MINUTE, 0);
tc.set(Calendar.SECOND, 0);
tc.set(Calendar.MILLISECOND, 0);
Calendar td = Calendar.getInstance();
td.set(Calendar.DAY_OF_MONTH, 1);
td.set(Calendar.HOUR_OF_DAY, 0);
td.set(Calendar.MINUTE, 0);
td.set(Calendar.SECOND, 0);
td.set(Calendar.MILLISECOND, 0);
return tc.equals(td);
}
/**
* @Title: isThisYear
* @Description: 是否是今年
* @param day
* @return
* @throws
*/
public static boolean isThisYear(Date day) {
java.util.Calendar tc = Calendar.getInstance();
tc.setTime(day);
Calendar td = Calendar.getInstance();
int ayear = tc.get(Calendar.YEAR);
int byear = td.get(Calendar.YEAR);
return ayear == byear ? true : false;
}
/**
* 判断时间小于或者等于当月
*
* @param day
* 时间
* @return
*/
public static boolean isLessOrEquThisMonth(Date day) {
java.util.Calendar tc = Calendar.getInstance();
tc.setTime(day);
tc.set(Calendar.DAY_OF_MONTH, 1);
tc.set(Calendar.HOUR_OF_DAY, 0);
tc.set(Calendar.MINUTE, 0);
tc.set(Calendar.SECOND, 0);
tc.set(Calendar.MILLISECOND, 0);
Calendar td = Calendar.getInstance();
td.set(Calendar.DAY_OF_MONTH, 1);
td.set(Calendar.HOUR_OF_DAY, 0);
td.set(Calendar.MINUTE, 0);
td.set(Calendar.SECOND, 0);
td.set(Calendar.MILLISECOND, 0);
return tc.before(td) || tc.equals(td);
}
/**
* 判断系统时间是否是当月1号
* @return
*/
public static boolean systimeIsMonthFirstDay() {
Calendar cal = Calendar.getInstance();
int day = cal.get(Calendar.DAY_OF_MONTH);
if(day == 1) return true;
return false;
}
/**
* @Title: isThisYear
* @Description: 判断day日期的年份是否大于今年
* @param day
* @return
* @throws
*/
public static boolean isGreaterThisYear(Date day) {
java.util.Calendar tc = Calendar.getInstance();
tc.setTime(day);
Calendar td = Calendar.getInstance();
return tc.get(Calendar.YEAR) > td.get(Calendar.YEAR);
}
/**
* @Title: isToday
* @Description: 判断day日期是否是今天
* @param day
* @return
* @throws
*/
public static boolean isToday(Date day) {
java.util.Calendar tc = Calendar.getInstance();
tc.setTime(day);
Calendar td = Calendar.getInstance();
return tc.get(Calendar.YEAR) == td.get(Calendar.YEAR)
&& tc.get(Calendar.MONTH) == td.get(Calendar.MONTH)
&& tc.get(Calendar.DAY_OF_MONTH) == td
.get(Calendar.DAY_OF_MONTH);
}
/**
* @Title: getBetweenYearDate
* @Description: 获取两个年跨度的所有年份 如:2011-2013 返回:2011、2012、2013
* @param start
* @param end
* @return
* @throws
*/
public static List<Date> getBetweenYearDate(Date start, Date end) {
List<Date> result = new ArrayList<Date>();
if (start.after(end))
return result;
Date startMonth = getBeginOfMonth(start);
while (!startMonth.after(end)) {
result.add(startMonth);
startMonth = changeDate(startMonth, 1, Calendar.YEAR);
}
return result;
}
/**
* @Title: getBetweenMonthDate
* @Description: 获取两个月跨度的所有月份 如:2013/05-2013/07 返回:2013/05、2013/06、2013/07
* @param start
* @param end
* @return
* @throws
*/
public static List<Date> getBetweenMonthDate(Date start, Date end) {
List<Date> result = new ArrayList<Date>();
if (start.after(end))
return result;
Date startMonth = getBeginOfMonth(start);
while (!startMonth.after(end)) {
result.add(startMonth);
startMonth = changeDate(startMonth, 1, Calendar.MONTH);
}
return result;
}
/**
* @Title: getBetweenWeekDate
* @Description: 获取两个日跨度的所有周日期
* @param start
* @param end
* @return
* @throws
*/
public static List<Date> getBetweenWeekDate(Date start, Date end) {
List<Date> result = new ArrayList<Date>();
if (start.after(end))
return result;
Date startMonth = getBeginOfWeek(start);
while (!startMonth.after(end)) {
result.add(startMonth);
startMonth = changeDate(startMonth, 1, Calendar.WEEK_OF_YEAR);
}
return result;
}
/**
* @Title: getBetweenDayDate
* @Description: 获取两个日跨度的所有日期 如:2013/05/06-2013/05/08 返回:2013/05/06、2013/05/07、2013/05/08
* @param start
* @param end
* @return
* @throws
*/
public static List<Date> getBetweenDayDate(Date start, Date end) {
List<Date> result = new ArrayList<Date>();
if (start.after(end))
return result;
Date startMonth = getBeginOfDay(start);
while (!startMonth.after(end)) {
result.add(startMonth);
startMonth = changeDate(startMonth, 1, Calendar.DATE);
}
return result;
}
/**
* @Title: _getBetweenDayDate
* @Description: 获取两个日跨度的所有日期 如:2013/05/06-2013/05/08 返回:2013/05/07 PS:不包含起始日期
* @param start
* @param end
* @return
* @throws
*/
public static List<Date> _getBetweenDayDate(Date start, Date end) {
List<Date> result = new ArrayList<Date>();
if (start.after(end))
return result;
Date startDay = getBeginOfDay(start);
while (!startDay.after(end)) {
if(!isSameDay(start, startDay) && !isSameDay(end, startDay)) result.add(startDay);
startDay = changeDate(startDay, 1, Calendar.DATE);
}
return result;
}
/**
* @Title: getHourInDay
* @Description: 获取某一天的第几小时时间
* @param day 某天
* @param hour 小时 0-24
* @return
* @throws
*/
public static Date getHourInDay(Date day, int hour) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(day);
calendar.set(Calendar.HOUR_OF_DAY, hour);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MILLISECOND, 0);
return calendar.getTime();
}
/**
* 修改日期,根据字段和步长
*
* @param time
* 日期
* @param amount
* 步长
* @param field
* 字段 Calendar内常量
* @return
*/
public static Date changeDate(Date time, int amount, int field) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(time);
calendar.add(field, amount);
return calendar.getTime();
}
/**
* 获取当前时间是星期几
* @param date
* @param language 语言(en英文显示,否则中文显示)
* @return
*/
public static String getWeekName(Date date,String language) {
String weekDay = "";
String[] weekDays = null;
if(language.equals("en")){
weekDays = new String[]{ "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" };
//weekDays = new String[]{ "S", "M", "T", "W", "T", "F", "S" };
}else{
weekDays = new String[]{ "星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六" };
}
Calendar cal = Calendar.getInstance();
if (date == null) {
weekDay = "--";
} else {
cal.setTime(date);
int w = cal.get(Calendar.DAY_OF_WEEK) - 1;
if (w < 0) w = 0;
weekDay = weekDays[w];
}
return weekDay;
}
/**
* @Title: getWeekOfDate
* @Description: 传入一个时间,判断该时间是星期几
* @param 时间
* @return 星期几
* @throws
*/
public static String getWeekOfDate(Date date) {
String weekDay = "";
String[] weekDays = { "星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六" };
Calendar cal = Calendar.getInstance();
if (date == null) {
weekDay = "--";
} else {
cal.setTime(date);
int w = cal.get(Calendar.DAY_OF_WEEK) - 1;
if (w < 0) w = 0;
weekDay = weekDays[w];
}
return weekDay;
}
/**
* 计算当前时间是当年里的第几周
* @param date
* @return
*/
public static int getWeekCountOfDate(Date date){
Calendar cal = Calendar.getInstance();
cal.setTime(date);
return cal.get(Calendar.WEEK_OF_YEAR);
}
/**
* 计算两个时间之间有几个周
* @param sDate
* @param eDate
* @return
*/
public static int getSumWeekDate(Date sDate,Date eDate){
Calendar cal = Calendar.getInstance();
cal.setTime(sDate);
int start = cal.get(Calendar.WEEK_OF_YEAR);
cal.setTime(eDate);
int end = cal.get(Calendar.WEEK_OF_YEAR);
return end-start+1;
}
/**
* @Title: getMonthChineseDescOfDate
* @Description: 传入一个时间,判断该时间是几月
* @param 时间
* @return 月
* @throws
*/
public static String getMonthChineseDescOfDate(Date date) {
String month = "";
String[] days = { "一月", "二月", "三月", "四月", "五月", "六月", "七月","八月","九月","十月","十一月","十二月"};
Calendar cal = Calendar.getInstance();
if (date == null) {
month = "--";
} else {
cal.setTime(date);
int w = cal.get(Calendar.MONTH) ;
if (w < 0) w = 0;
month = days[w];
}
return month;
}
// ------------------------------------------------------------------------------
public static String getTimeString(Timestamp tsp) {
if (tsp == null)
return "";
return getTimeString(new Date(tsp.getTime()));
}
// ------------------------------------------------------------------------------
public static String getTimeString(java.util.Date date) {
SimpleDateFormat formatter = new SimpleDateFormat(LONG_FORM);
return formatter.format(date).trim();
}
public static String getShortTimeString(java.util.Date date) {
SimpleDateFormat formatter = new SimpleDateFormat("HH:mm:ss");
return formatter.format(date).trim();
}
/*
* public static String getTimeString(java.sql.Date date) { SimpleDateFormat
* formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); return
* formatter.format(date).trim(); }
*/
// ------------------------------------------------------------------------------
public static String getDateString(java.util.Date date) {
if (date == null)
return "";
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
return formatter.format(date).trim();
}
/*
* public static String getDateString(java.sql.Date date) { SimpleDateFormat
* formatter = new SimpleDateFormat("yyyy-MM-dd"); return
* formatter.format(date).trim(); }
*/
// ------------------------------------------------------------------------------
public static String to_char(Timestamp tsp, String format) {
if (tsp == null)
return "";
return to_char(new Date(tsp.getTime()), format);
}
// ------------------------------------------------------------------------------
public static String to_char(Date date, String format) {
SimpleDateFormat formatter = new SimpleDateFormat(format);
return formatter.format(date).trim();
}
// ------------------------------------------------------------------------------
/**
* 字符串转换为日期java.util.Date
*
* @param dateText
* 字符串
* @param format
* 日期格式
* @return
*/
public static Date paseDate(String dateText, String format) {
if (dateText == null) {
return null;
}
DateFormat df = null;
try {
if (format == null) {
df = new SimpleDateFormat();
} else {
df = new SimpleDateFormat(format);
}
// setLenient avoids allowing dates like 9/32/2001
// which would otherwise parse to 10/2/2001
df.setLenient(false);
return df.parse(dateText);
} catch (ParseException e) {
return null;
}
}
public static Date paseDate(String dateText) {
if (dateText == null) {
return null;
}
String format = "yyyyMMdd";
if(dateText.length() == 4) format = "yyyy";
if(dateText.length() == 6) format = "yyyyMM";
DateFormat df = null;
try {
if (format == null) {
df = new SimpleDateFormat();
} else {
df = new SimpleDateFormat(format);
}
// setLenient avoids allowing dates like 9/32/2001
// which would otherwise parse to 10/2/2001
df.setLenient(false);
return df.parse(dateText);
} catch (ParseException e) {
return null;
}
}
// ------------------------------------------------------------------------------
/**
* 返回本周,本月,本年时间范围的开始,结束日期,日期格式:yyyy-MM-dd
*
* @param selType
* 1:本周 2:本月 3:本年
* @return 开始,结束日期字符数组
*/
public static final String[] getDateRange(int selType) {
String startDate = null, endDate = null;
Calendar cd = Calendar.getInstance();
int year = cd.get(Calendar.YEAR);
int month = cd.get(Calendar.MONTH) + 1;
Calendar cdTmp = Calendar.getInstance();
int i;
switch (selType) {
case 1: // 本周
i = cd.get(Calendar.DAY_OF_WEEK) - 1;
cdTmp.setTime(new Date(cd.getTime().getTime() - i * 3600 * 24
* 1000));
startDate = cdTmp.get(Calendar.YEAR) + "-"
+ (cdTmp.get(Calendar.MONTH) + 1) + "-"
+ cdTmp.get(Calendar.DAY_OF_MONTH);
i = 7 - cd.get(Calendar.DAY_OF_WEEK);
cdTmp.setTime(new Date(cd.getTime().getTime() + i * 3600 * 24
* 1000));
endDate = cdTmp.get(Calendar.YEAR) + "-"
+ (cdTmp.get(Calendar.MONTH) + 1) + "-"
+ cdTmp.get(Calendar.DAY_OF_MONTH);
break;
case 2: // 本月
startDate = year + "-" + month + "-01";
switch (month) {
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
endDate = year + "-" + month + "-31";
break;
case 2:
if (isLeapYear(year))
endDate = year + "-" + month + "-29";
else
endDate = year + "-" + month + "-28";
break;
default:
endDate = year + "-" + month + "-30";
}
break;
case 3: // 本年
startDate = year + "-01-01";
endDate = year + "-12-31";
break;
default:
startDate = "2000-01-01";
endDate = "2100-01-01";
} // switch
return new String[] { startDate, endDate };
}
// ------------------------------------------------------------------------------
/**
* 判断是否闰年
*
* @param y
* 年份
* @return true or false
*/
public static final boolean isLeapYear(int y) {
if (y % 4 == 0) {
if (y % 100 == 0) {
if (y % 400 == 0)
return true;
else
return false;
} else {
return true;
} // else
} // if
return false;
}
/**
* 获取两个日期间的月份间隔
*
* @param date
* @param date
* @return int
*/
public static final int monthsIndays(Date early, Date late) {
Calendar c1 = Calendar.getInstance();
Calendar c2 = Calendar.getInstance();
c1.setTime(early);
c2.setTime(late);
int earlyYear = c1.get(Calendar.YEAR);
int earlyMonth = c1.get(Calendar.MONTH);
int lateYear = c2.get(Calendar.YEAR);
int lateMonth = c2.get(Calendar.MONTH);
int months = (lateYear - earlyYear) * 12 + lateMonth - earlyMonth + 1;
return months;
}
// ------查看是否闰年----------------
public static final boolean checkLeapYear(int Year) {
boolean isLeapYear = false;
if (Year % 4 == 0 && Year % 100 != 0) {
isLeapYear = true;
}
if (Year % 400 == 0)
isLeapYear = true;
else if (Year % 4 != 0) {
isLeapYear = false;
}
return isLeapYear;
}
// --------计算当月天数---------------
// 要输入年份的原因是要判断二月29天还是28天
public static final int checkMonth(int Month, int Year) {
int Dates = 0;
if (Month < 0 || Month > 12) {
System.out.println("Month Error");
}
if (Month == 1 || Month == 3 || Month == 5 || Month == 7 || Month == 8
|| Month == 10 || Month == 12) {
Dates = 31;
}
if (Month == 2 && checkLeapYear(Year)) {
Dates = 29;
}
if (Month == 2 && !checkLeapYear(Year)) {
Dates = 28;
}
if (Month == 4 || Month == 6 || Month == 9 || Month == 11) {
Dates = 30;
}
return Dates;
}
// 返回early/later之间的,所有日期,不包括later
// public static List<Date> getEachDateList(Date early, Date later) {
// List<Date> dates = new ArrayList<Date>();
// int days = DateTimeUtil.daysBetween(early, later);
//
// for (int i = 0; i < days; i++) {
// dates.add(DateTimeUtil.dateIncreaseByDay(early, i));
// }
// return dates;
// }
public static String parse2WeekDisplay(Date date){
//13'05W2
TimeZone tz = new SimpleTimeZone(-28800000,"America/Los_Angeles");
Locale loc = new Locale("en","us");
Calendar cal = Calendar.getInstance(tz,loc);
//TimeZone:Asia/Shanghai Locale:zh_CN(lan:zh,country:CN)
//Calendar cal = Calendar.getInstance(TimeZone.getDefault(),Locale.getDefault());
cal.setTime(getEndOfWeek(date));
String year = String.valueOf(cal.get(Calendar.YEAR));
String month = String.valueOf(cal.get(Calendar.MONTH) + 1);
int week = cal.get(Calendar.DAY_OF_WEEK_IN_MONTH);
//int week = cal.get(Calendar.WEEK_OF_MONTH);
return year.substring(2, 4) + "'" + ((month.length() == 1)?("0" + month):month) + "W" + week;
}
/**
* 将时间转成(12'06)格式
* @param date
*/
public static String parse2MonthFormat(Date date){
//2012-06-01 转成 12'06
Calendar cal = Calendar.getInstance();
cal.setTime(date);
String year = String.valueOf(cal.get(Calendar.YEAR));
String month = String.valueOf(cal.get(Calendar.MONTH) + 1);
return year.substring(2, 4) + "'" + (month.length() < 2 ? "0"+month : month);
}
/**
* 返回date是本月的第几天
* @param date
* @return
*/
public static int getDayOfMonth(Date date){
Calendar cal = Calendar.getInstance();
cal.setTime(date);
return cal.get(Calendar.DAY_OF_MONTH);
}
/**
* 获取某个月的总天数
* @param month
* @return
*/
public static int getTotalCountDayInMonth(Date month) {
java.util.Calendar cal = Calendar.getInstance();
cal.setTime(month);
return cal.getActualMaximum(Calendar.DAY_OF_MONTH);
}
/**
* 返回同比天(上一年的这一天)
* @param date
* @return
*/
public static Date getDateOnDate(Date date){
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.add(Calendar.YEAR, -1);
return cal.getTime();
}
/**
* 返回同比周
* @param date
* @return
*/
public static Date getWeekOnWeek(Date date){
TimeZone tz = new SimpleTimeZone(-28800000,"America/Los_Angeles");
Locale loc = new Locale("en","us");
Calendar cal = Calendar.getInstance(tz,loc);
cal.setTime(date);
int weekOfYear = cal.get(Calendar.WEEK_OF_YEAR);
cal.setTime(add(date,-1,Calendar.YEAR)); // getLastYear
cal.set(Calendar.WEEK_OF_YEAR, weekOfYear); // 如果当年只有52周,设值为53时,会来到今年的第1周
int lastYearWeekOfYear = cal.get(Calendar.WEEK_OF_YEAR);
// 如果今年有53周,但上一年只有52周时,返回null
return (weekOfYear == lastYearWeekOfYear)?getBeginOfWeek(cal.getTime()):null;
}
/**
* 返回年份值
* @param date
* @return
*/
public static String getYear(Date date){
Calendar cal = Calendar.getInstance();
cal.setTime(date);
return String.valueOf(cal.get(Calendar.YEAR));
}
/**
* 返回月份值
* @param date
* @return
*/
public static String getMonth(Date date){
Calendar cal = Calendar.getInstance();
cal.setTime(date);
return String.valueOf(cal.get(Calendar.MONTH)+1);
}
/**
* 根据date返回中文的day显示
* @param date
* @return
*/
public static String getDayChineseDescOfDate(Date date){
if(date != null){
Calendar c = Calendar.getInstance();
c.setTime(date);
return c.get(Calendar.DAY_OF_MONTH)+"日";
}else
return "";
}
/**
* 根据date返回本月的第一周的首日,以周一为开始
* @param date
* @return
*/
public static Date getFirstWeekOfMonth(Date date){
TimeZone tz = new SimpleTimeZone(-28800000,"America/Los_Angeles");
Locale loc = new Locale("en","us");
Calendar cal = Calendar.getInstance(tz,loc);
cal.setTime(getEndOfWeek(date));
int week = cal.get(Calendar.DAY_OF_WEEK_IN_MONTH);
cal.add(Calendar.WEEK_OF_MONTH,1-week);
return getBeginOfWeek(cal.getTime());
}
/**
* 根据date返回本月所有星期的首日,以周一为开始
* @param date
* @return
*/
public static List<Date> getWeeksOfMonth(Date date){
List<Date> dates = new ArrayList<Date>();
Date currentMonthBegin = getFirstWeekOfMonth(date);
Date nextMonthBegin = getFirstWeekOfMonth(add(date,1,Calendar.MONTH));
while(currentMonthBegin.before(nextMonthBegin)){
dates.add(currentMonthBegin);
currentMonthBegin = add(currentMonthBegin,1,Calendar.WEEK_OF_MONTH);
}
return dates;
}
/**
* 根据monthStrs(即一串以逗号分隔的数字),返回年份+月份信息
* 如月份为5,7,则返回Date类型的(year)/05/01,(year)/07/01
* @param date
* @param monthStrs
* @return
*/
public static List<Date> getMonthsDateByOption(String year , String monthStrs){
Calendar cal = Calendar.getInstance();
List<Date> dates = new ArrayList<Date>();
if(monthStrs != null && !"".equals(monthStrs.trim())){
for(String month : monthStrs.split(",")){
cal.set(Calendar.YEAR, Integer.parseInt(year));
cal.set(Calendar.MONTH, Integer.parseInt(month)-1);
dates.add(getBeginOfMonth(cal.getTime()));
}
}
return dates;
}
/**
* 根据dayStrs(即一串以逗号分隔的数字),返回年份月份+day信息
* 如月份为5,7,则返回Date类型的(year)/(month)/05,(year)/(month)/07
* @param date
* @param dayStrs
* @return
*/
public static List<Date> getDaysDateByOption(String year , String month , String dayStrs){
Calendar cal = Calendar.getInstance();
List<Date> dates = new ArrayList<Date>();
if(dayStrs != null && !"".equals(dayStrs.trim())){
for(String day : dayStrs.split(",")){
cal.set(Calendar.YEAR, Integer.parseInt(year));
cal.set(Calendar.MONTH, Integer.parseInt(month)-1);
cal.set(Calendar.DATE, Integer.parseInt(day));
dates.add(getBeginOfDay(cal.getTime()));
}
}
return dates;
}
public static Date toDate(Long millis){
Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(millis);
return cal.getTime();
}
public static void main(String[] args) {
//1372608000 1367337600
// 1372521600 1376150400
// System.out.println(getTimeString(toDate(1367078400*1000l)));
// System.out.println(getTimeString(toDate(1370707200*1000l)));
/*Date date1 = new Date("2013/11/06");
Date date2 = new Date("2013/08/07");
List<Date> dates = _getBetweenDayDate(date1, date2);
for(Date d : dates) {
//System.out.println(format(d, LONG_FORM));
}*/
// Calendar cal = Calendar.getInstance();
// cal.setTime(date);
//System.out.println("当月第一天:"+systimeIsMonthFirstDay());
//2013-06-30 00:00:00
//2013-08-11 00:00:00
}
}
ErrorTypeUtil 枚举设置errorCode和errorMsg十分方便
package cn.ways.gtids.common.utils;
/**
* Description:
* Author: zhaohaiyong
* Modifier:
* Modify Date:
* Modify Note:
* version:
*/
public enum ErrorTypeUtil {
E_1000(1000), //请求地址错误
E_1010(1010), //用户名或密码错误
E_1011(1011), //手势密码错误
E_1012(1012), //设备未绑定
E_1002(1002), //数据加载异常
E_1003(1003), //登录超时(需重新登录)
E_1004(1004); //其他的类型错误
private int val;
public String getErrorMsg(){
switch (val) {
case 1000:
return "登录失败,用户名或者密码不正确!";
case 1010:
return "登录失败,用户名或者密码不正确!";
case 1002:
return "数据加载失败,请检查网络是否正确或稍后再试!";
case 1003:
return "登录超时,请稍后再试!";
case 1004:
return "系统异常,请稍后再试!";
}
return "";
}
public String getErrorCode(){
switch (val) {
case 1000:
return "1000";
case 1010:
return "1010";
case 1011:
return "1011";
case 1012:
return "1012";
case 1002:
return "1002";
case 1003:
return "1003";
case 1004:
return "1004";
}
return "1004";
}
private ErrorTypeUtil(int val) {
this.val = val;
}
public int getVal() {
return val;
}
public void setVal(int val) {
this.val = val;
}
public static void main(String[] args) {
System.out.println(ErrorTypeUtil.E_1002.getErrorCode());
}
}
HttpRequestUtil java请求接口工具类
package cn.ways.gtids.common.utils;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.Map;
import java.util.Vector;
import com.alibaba.fastjson.JSONObject;
/**
* @ClassName:HttpRequestUtil
* @Description: Http请求
* @author Zhaohy
* @Modifier:
* @Modify Date:
* @Modify Note:
* @version
*/
public class HttpRequestUtil {
private String defaultContentEncoding;
public HttpRequestUtil() {
this.defaultContentEncoding = Charset.defaultCharset().name();
}
/**
*#############################test#########################
*/
public static void main(String[] args) {
try {
HttpRequestUtil ru = new HttpRequestUtil();
ru.setDefaultContentEncoding("UTF-8");
Map<String, String> params = new HashMap<String, String>();
params.put("ip", "192.168.3.136");
params.put("format", "json");
String url = "http://int.dpool.sina.com.cn/iplookup/iplookup.php";
ResponseObj obj = ru.sendPost(url, params);
String resStr = obj.getContent();
String address = "";
if(!"-1".equals(resStr) && !"-2".equals(resStr)) {
JSONObject json = JSONObject.parseObject(resStr);
String country = json.containsKey("country") ? new String(json.getString("country")) : "";
String province = json.containsKey("province") ? new String(json.getString("province")) : "";
String city = json.containsKey("city") ? new String(json.getString("city")) : "";
String isp = json.containsKey("isp") ? new String(json.getString("isp")) : "";
address = country + " " + province + " " + " " + city + " " + isp;
}
System.out.println("返回内容:"+address);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* 发送GET请求
*
* @param urlString
* URL地址
* @return 响应对象
* @throws IOException
*/
public ResponseObj sendGet(String urlString) throws IOException {
return this.send(urlString, "GET", null, null);
}
/**
* 发送GET请求
*
* @param urlString
* URL地址
* @param params
* 参数集合
* @return 响应对象
* @throws IOException
*/
public ResponseObj sendGet(String urlString, Map<String, String> params)
throws IOException {
return this.send(urlString, "GET", params, null);
}
/**
* 发送GET请求
*
* @param urlString
* URL地址
* @param params
* 参数集合
* @param propertys
* 请求属性
* @return 响应对象
* @throws IOException
*/
public ResponseObj sendGet(String urlString, Map<String, String> params,
Map<String, String> propertys) throws IOException {
return this.send(urlString, "GET", params, propertys);
}
/**
* 发送POST请求
*
* @param urlString
* URL地址
* @return 响应对象
* @throws IOException
*/
public ResponseObj sendPost(String urlString) throws IOException {
return this.send(urlString, "POST", null, null);
}
/**
* 发送POST请求
*
* @param urlString
* URL地址
* @param params
* 参数集合
* @return 响应对象
* @throws IOException
*/
public ResponseObj sendPost(String urlString, Map<String, String> params)
throws IOException {
return this.send(urlString, "POST", params, null);
}
/**
* 发送POST请求
*
* @param urlString
* URL地址
* @param params
* 参数集合
* @param propertys
* 请求属性
* @return 响应对象
* @throws IOException
*/
public ResponseObj sendPost(String urlString, Map<String, String> params,
Map<String, String> propertys) throws IOException {
return this.send(urlString, "POST", params, propertys);
}
/**
* 发送HTTP请求
*
* @param urlString
* @return 响映对象
* @throws IOException
*/
private ResponseObj send(String urlString, String method,
Map<String, String> parameters, Map<String, String> propertys)
throws IOException {
HttpURLConnection urlConnection = null;
if (method.equalsIgnoreCase("GET") && parameters != null) {
StringBuffer param = new StringBuffer();
int i = 0;
for (String key : parameters.keySet()) {
if (i == 0)
param.append("?");
else
param.append("&");
param.append(key).append("=").append(parameters.get(key));
i++;
}
urlString += param;
}
URL url = new URL(urlString);
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod(method);
urlConnection.setDoOutput(true);
urlConnection.setDoInput(true);
urlConnection.setUseCaches(false);
if (propertys != null)
for (String key : propertys.keySet()) {
urlConnection.addRequestProperty(key, propertys.get(key));
}
if (method.equalsIgnoreCase("POST") && parameters != null) {
StringBuffer param = new StringBuffer();
for (String key : parameters.keySet()) {
param.append("&");
param.append(key).append("=").append(parameters.get(key));
}
urlConnection.getOutputStream().write(param.toString().getBytes());
urlConnection.getOutputStream().flush();
urlConnection.getOutputStream().close();
}
return this.makeContent(urlString, urlConnection);
}
/**
* 得到响应对象
*
* @param urlConnection
* @return 响应对象
* @throws IOException
*/
private ResponseObj makeContent(String urlString,
HttpURLConnection urlConnection) throws IOException {
ResponseObj httpRs = new ResponseObj();
try {
InputStream in = urlConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(
new InputStreamReader(in));
httpRs.contentCollection = new Vector<String>();
StringBuffer temp = new StringBuffer();
String line = bufferedReader.readLine();
while (line != null) {
httpRs.contentCollection.add(line);
temp.append(line).append("\r\n");
line = bufferedReader.readLine();
}
bufferedReader.close();
String ecod = urlConnection.getContentEncoding();
if (ecod == null)
ecod = this.defaultContentEncoding;
httpRs.urlString = urlString;
httpRs.defaultPort = urlConnection.getURL().getDefaultPort();
httpRs.file = urlConnection.getURL().getFile();
httpRs.host = urlConnection.getURL().getHost();
httpRs.path = urlConnection.getURL().getPath();
httpRs.port = urlConnection.getURL().getPort();
httpRs.protocol = urlConnection.getURL().getProtocol();
httpRs.query = urlConnection.getURL().getQuery();
httpRs.ref = urlConnection.getURL().getRef();
httpRs.userInfo = urlConnection.getURL().getUserInfo();
httpRs.content = new String(temp.toString().getBytes(), ecod);
httpRs.contentEncoding = ecod;
httpRs.code = urlConnection.getResponseCode();
httpRs.message = urlConnection.getResponseMessage();
httpRs.contentType = urlConnection.getContentType();
httpRs.method = urlConnection.getRequestMethod();
httpRs.connectTimeout = urlConnection.getConnectTimeout();
httpRs.readTimeout = urlConnection.getReadTimeout();
return httpRs;
} catch (IOException e) {
throw e;
} finally {
if (urlConnection != null)
urlConnection.disconnect();
}
}
/**
* 默认的响应字符集
*/
public String getDefaultContentEncoding() {
return this.defaultContentEncoding;
}
/**
* 设置默认的响应字符集
*/
public void setDefaultContentEncoding(String defaultContentEncoding) {
this.defaultContentEncoding = defaultContentEncoding;
}
}
上面的工具类中用到的响应对象实体类
package cn.ways.gtids.common.utils;
import java.util.Vector;
/**
* @ClassName:ResponseObj
* @Description: 相应对象
* @author Zhaohy
* @Modifier:
* @Modify Date:
* @Modify Note:
* @version
*/
public class ResponseObj {
public String urlString;
public int defaultPort;
public String file;
public String host;
public String path;
public int port;
public String protocol;
public String query;
public String ref;
public String userInfo;
public String contentEncoding;
public String content;
public String contentType;
public int code;
public String message;
public String method;
public int connectTimeout;
public int readTimeout;
public Vector<String> contentCollection;
public String getContent() {
return content;
}
public String getContentType() {
return contentType;
}
public int getCode() {
return code;
}
public String getMessage() {
return message;
}
public Vector<String> getContentCollection() {
return contentCollection;
}
public String getContentEncoding() {
return contentEncoding;
}
public String getMethod() {
return method;
}
public int getConnectTimeout() {
return connectTimeout;
}
public int getReadTimeout() {
return readTimeout;
}
public String getUrlString() {
return urlString;
}
public int getDefaultPort() {
return defaultPort;
}
public String getFile() {
return file;
}
public String getHost() {
return host;
}
public String getPath() {
return path;
}
public int getPort() {
return port;
}
public String getProtocol() {
return protocol;
}
public String getQuery() {
return query;
}
public String getRef() {
return ref;
}
public String getUserInfo() {
return userInfo;
}
}
MD5Util MD5加密工具类
package cn.ways.gtids.common.utils;
import java.util.Date;
/************************************************
MD5 算法的Java Bean
@author:zhaohy
*************************************************/
/*************************************************
md5 类实现了RSA Data Security, Inc.在提交给IETF
的RFC1321中的MD5 message-digest 算法。
*************************************************/
public class MD5Util {
/* 下面这些S11-S44实际上是一个4*4的矩阵,在原始的C实现中是用#define 实现的,
这里把它们实现成为static final是表示了只读,切能在同一个进程空间内的多个
Instance间共享*/
static final int S11 = 7;
static final int S12 = 12;
static final int S13 = 17;
static final int S14 = 22;
static final int S21 = 5;
static final int S22 = 9;
static final int S23 = 14;
static final int S24 = 20;
static final int S31 = 4;
static final int S32 = 11;
static final int S33 = 16;
static final int S34 = 23;
static final int S41 = 6;
static final int S42 = 10;
static final int S43 = 15;
static final int S44 = 21;
static final byte[] PADDING = {
-128, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
/* 下面的三个成员是MD5计算过程中用到的3个核心数据,在原始的C实现中
被定义到MD5_CTX结构中
*/
private long[] state = new long[4]; // state (ABCD)
private long[] count = new long[2]; // number of bits, modulo 2^64 (lsb first)
private byte[] buffer = new byte[64]; // input buffer
/* digestHexStr是MD5的唯一一个公共成员,是最新一次计算结果的
16进制ASCII表示.
*/
public String digestHexStr;
/* digest,是最新一次计算结果的2进制内部表示,表示128bit的MD5值.
*/
private byte[] digest = new byte[16];
/*
getMD5ofStr是类MD5最主要的公共方法,入口参数是你想要进行MD5变换的字符串
返回的是变换完的结果,这个结果是从公共成员digestHexStr取得的.
*/
public String getMD5ofStr(String inbuf) {
md5Init();
md5Update(inbuf.getBytes(), inbuf.length());
md5Final();
digestHexStr = "";
for (int i = 0; i < 16; i++) {
digestHexStr += byteHEX(digest[i]);
}
return digestHexStr;
}
// 这是MD5这个类的标准构造函数,JavaBean要求有一个public的并且没有参数的构造函数
public MD5Util() {
md5Init();
return;
}
/* md5Init是一个初始化函数,初始化核心变量,装入标准的幻数 */
private void md5Init() {
count[0] = 0L;
count[1] = 0L;
///* Load magic initialization constants.
state[0] = 0x67452301L;
state[1] = 0xefcdab89L;
state[2] = 0x98badcfeL;
state[3] = 0x10325476L;
return;
}
/* F, G, H ,I 是4个基本的MD5函数,在原始的MD5的C实现中,由于它们是
简单的位运算,可能出于效率的考虑把它们实现成了宏,在java中,我们把它们
实现成了private方法,名字保持了原来C中的。 */
private long F(long x, long y, long z) {
return (x & y) | ( (~x) & z);
}
private long G(long x, long y, long z) {
return (x & z) | (y & (~z));
}
private long H(long x, long y, long z) {
return x ^ y ^ z;
}
private long I(long x, long y, long z) {
return y ^ (x | (~z));
}
/*
FF,GG,HH和II将调用F,G,H,I进行近一步变换
FF, GG, HH, and II transformations for rounds 1, 2, 3, and 4.
Rotation is separate from addition to prevent recomputation.
*/
private long FF(long a, long b, long c, long d, long x, long s,
long ac) {
a += F(b, c, d) + x + ac;
a = ( (int) a << s) | ( (int) a >>> (32 - s));
a += b;
return a;
}
private long GG(long a, long b, long c, long d, long x, long s,
long ac) {
a += G(b, c, d) + x + ac;
a = ( (int) a << s) | ( (int) a >>> (32 - s));
a += b;
return a;
}
private long HH(long a, long b, long c, long d, long x, long s,
long ac) {
a += H(b, c, d) + x + ac;
a = ( (int) a << s) | ( (int) a >>> (32 - s));
a += b;
return a;
}
private long II(long a, long b, long c, long d, long x, long s,
long ac) {
a += I(b, c, d) + x + ac;
a = ( (int) a << s) | ( (int) a >>> (32 - s));
a += b;
return a;
}
/*
md5Update是MD5的主计算过程,inbuf是要变换的字节串,inputlen是长度,这个
函数由getMD5ofStr调用,调用之前需要调用md5init,因此把它设计成private的
*/
private void md5Update(byte[] inbuf, int inputLen) {
int i, index, partLen;
byte[] block = new byte[64];
index = (int) (count[0] >>> 3) & 0x3F;
// /* Update number of bits */
if ( (count[0] += (inputLen << 3)) < (inputLen << 3))
count[1]++;
count[1] += (inputLen >>> 29);
partLen = 64 - index;
// Transform as many times as possible.
if (inputLen >= partLen) {
md5Memcpy(buffer, inbuf, index, 0, partLen);
md5Transform(buffer);
for (i = partLen; i + 63 < inputLen; i += 64) {
md5Memcpy(block, inbuf, 0, i, 64);
md5Transform(block);
}
index = 0;
}
else
i = 0;
///* Buffer remaining input */
md5Memcpy(buffer, inbuf, index, i, inputLen - i);
}
/*
md5Final整理和填写输出结果
*/
private void md5Final() {
byte[] bits = new byte[8];
int index, padLen;
///* Save number of bits */
Encode(bits, count, 8);
///* Pad out to 56 mod 64.
index = (int) (count[0] >>> 3) & 0x3f;
padLen = (index < 56) ? (56 - index) : (120 - index);
md5Update(PADDING, padLen);
///* Append length (before padding) */
md5Update(bits, 8);
///* Store state in digest */
Encode(digest, state, 16);
}
/* md5Memcpy是一个内部使用的byte数组的块拷贝函数,从input的inpos开始把len长度的
字节拷贝到output的outpos位置开始
*/
private void md5Memcpy(byte[] output, byte[] input,
int outpos, int inpos, int len) {
int i;
for (i = 0; i < len; i++)
output[outpos + i] = input[inpos + i];
}
/*
md5Transform是MD5核心变换程序,有md5Update调用,block是分块的原始字节
*/
private void md5Transform(byte block[]) {
long a = state[0], b = state[1], c = state[2], d = state[3];
long[] x = new long[16];
Decode(x, block, 64);
/* Round 1 */
a = FF(a, b, c, d, x[0], S11, 0xd76aa478L); /* 1 */
d = FF(d, a, b, c, x[1], S12, 0xe8c7b756L); /* 2 */
c = FF(c, d, a, b, x[2], S13, 0x242070dbL); /* 3 */
b = FF(b, c, d, a, x[3], S14, 0xc1bdceeeL); /* 4 */
a = FF(a, b, c, d, x[4], S11, 0xf57c0fafL); /* 5 */
d = FF(d, a, b, c, x[5], S12, 0x4787c62aL); /* 6 */
c = FF(c, d, a, b, x[6], S13, 0xa8304613L); /* 7 */
b = FF(b, c, d, a, x[7], S14, 0xfd469501L); /* 8 */
a = FF(a, b, c, d, x[8], S11, 0x698098d8L); /* 9 */
d = FF(d, a, b, c, x[9], S12, 0x8b44f7afL); /* 10 */
c = FF(c, d, a, b, x[10], S13, 0xffff5bb1L); /* 11 */
b = FF(b, c, d, a, x[11], S14, 0x895cd7beL); /* 12 */
a = FF(a, b, c, d, x[12], S11, 0x6b901122L); /* 13 */
d = FF(d, a, b, c, x[13], S12, 0xfd987193L); /* 14 */
c = FF(c, d, a, b, x[14], S13, 0xa679438eL); /* 15 */
b = FF(b, c, d, a, x[15], S14, 0x49b40821L); /* 16 */
/* Round 2 */
a = GG(a, b, c, d, x[1], S21, 0xf61e2562L); /* 17 */
d = GG(d, a, b, c, x[6], S22, 0xc040b340L); /* 18 */
c = GG(c, d, a, b, x[11], S23, 0x265e5a51L); /* 19 */
b = GG(b, c, d, a, x[0], S24, 0xe9b6c7aaL); /* 20 */
a = GG(a, b, c, d, x[5], S21, 0xd62f105dL); /* 21 */
d = GG(d, a, b, c, x[10], S22, 0x2441453L); /* 22 */
c = GG(c, d, a, b, x[15], S23, 0xd8a1e681L); /* 23 */
b = GG(b, c, d, a, x[4], S24, 0xe7d3fbc8L); /* 24 */
a = GG(a, b, c, d, x[9], S21, 0x21e1cde6L); /* 25 */
d = GG(d, a, b, c, x[14], S22, 0xc33707d6L); /* 26 */
c = GG(c, d, a, b, x[3], S23, 0xf4d50d87L); /* 27 */
b = GG(b, c, d, a, x[8], S24, 0x455a14edL); /* 28 */
a = GG(a, b, c, d, x[13], S21, 0xa9e3e905L); /* 29 */
d = GG(d, a, b, c, x[2], S22, 0xfcefa3f8L); /* 30 */
c = GG(c, d, a, b, x[7], S23, 0x676f02d9L); /* 31 */
b = GG(b, c, d, a, x[12], S24, 0x8d2a4c8aL); /* 32 */
/* Round 3 */
a = HH(a, b, c, d, x[5], S31, 0xfffa3942L); /* 33 */
d = HH(d, a, b, c, x[8], S32, 0x8771f681L); /* 34 */
c = HH(c, d, a, b, x[11], S33, 0x6d9d6122L); /* 35 */
b = HH(b, c, d, a, x[14], S34, 0xfde5380cL); /* 36 */
a = HH(a, b, c, d, x[1], S31, 0xa4beea44L); /* 37 */
d = HH(d, a, b, c, x[4], S32, 0x4bdecfa9L); /* 38 */
c = HH(c, d, a, b, x[7], S33, 0xf6bb4b60L); /* 39 */
b = HH(b, c, d, a, x[10], S34, 0xbebfbc70L); /* 40 */
a = HH(a, b, c, d, x[13], S31, 0x289b7ec6L); /* 41 */
d = HH(d, a, b, c, x[0], S32, 0xeaa127faL); /* 42 */
c = HH(c, d, a, b, x[3], S33, 0xd4ef3085L); /* 43 */
b = HH(b, c, d, a, x[6], S34, 0x4881d05L); /* 44 */
a = HH(a, b, c, d, x[9], S31, 0xd9d4d039L); /* 45 */
d = HH(d, a, b, c, x[12], S32, 0xe6db99e5L); /* 46 */
c = HH(c, d, a, b, x[15], S33, 0x1fa27cf8L); /* 47 */
b = HH(b, c, d, a, x[2], S34, 0xc4ac5665L); /* 48 */
/* Round 4 */
a = II(a, b, c, d, x[0], S41, 0xf4292244L); /* 49 */
d = II(d, a, b, c, x[7], S42, 0x432aff97L); /* 50 */
c = II(c, d, a, b, x[14], S43, 0xab9423a7L); /* 51 */
b = II(b, c, d, a, x[5], S44, 0xfc93a039L); /* 52 */
a = II(a, b, c, d, x[12], S41, 0x655b59c3L); /* 53 */
d = II(d, a, b, c, x[3], S42, 0x8f0ccc92L); /* 54 */
c = II(c, d, a, b, x[10], S43, 0xffeff47dL); /* 55 */
b = II(b, c, d, a, x[1], S44, 0x85845dd1L); /* 56 */
a = II(a, b, c, d, x[8], S41, 0x6fa87e4fL); /* 57 */
d = II(d, a, b, c, x[15], S42, 0xfe2ce6e0L); /* 58 */
c = II(c, d, a, b, x[6], S43, 0xa3014314L); /* 59 */
b = II(b, c, d, a, x[13], S44, 0x4e0811a1L); /* 60 */
a = II(a, b, c, d, x[4], S41, 0xf7537e82L); /* 61 */
d = II(d, a, b, c, x[11], S42, 0xbd3af235L); /* 62 */
c = II(c, d, a, b, x[2], S43, 0x2ad7d2bbL); /* 63 */
b = II(b, c, d, a, x[9], S44, 0xeb86d391L); /* 64 */
state[0] += a;
state[1] += b;
state[2] += c;
state[3] += d;
}
/*Encode把long数组按顺序拆成byte数组,因为java的long类型是64bit的,
只拆低32bit,以适应原始C实现的用途
*/
private void Encode(byte[] output, long[] input, int len) {
int i, j;
for (i = 0, j = 0; j < len; i++, j += 4) {
output[j] = (byte) (input[i] & 0xffL);
output[j + 1] = (byte) ( (input[i] >>> 8) & 0xffL);
output[j + 2] = (byte) ( (input[i] >>> 16) & 0xffL);
output[j + 3] = (byte) ( (input[i] >>> 24) & 0xffL);
}
}
/*Decode把byte数组按顺序合成成long数组,因为java的long类型是64bit的,
只合成低32bit,高32bit清零,以适应原始C实现的用途
*/
private void Decode(long[] output, byte[] input, int len) {
int i, j;
for (i = 0, j = 0; j < len; i++, j += 4)
output[i] = b2iu(input[j]) |
(b2iu(input[j + 1]) << 8) |
(b2iu(input[j + 2]) << 16) |
(b2iu(input[j + 3]) << 24);
return;
}
/*
b2iu是我写的一个把byte按照不考虑正负号的原则的"升位"程序,因为java没有unsigned运算
*/
public static long b2iu(byte b) {
return b < 0 ? b & 0x7F + 128 : b;
}
/*byteHEX(),用来把一个byte类型的数转换成十六进制的ASCII表示,
因为java中的byte的toString无法实现这一点,我们又没有C语言中的
sprintf(outbuf,"%02X",ib)
*/
public static String byteHEX(byte ib) {
char[] Digit = {
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
'A', 'B', 'C', 'D', 'E', 'F'};
char[] ob = new char[2];
ob[0] = Digit[ (ib >>> 4) & 0X0F];
ob[1] = Digit[ib & 0X0F];
String s = new String(ob);
return s;
}
public static void main(String args[]) {
MD5Util m = new MD5Util();
//System.out.println("MD5 Test suite:");
//System.out.println("MD5(\"\"):" + m.getMD5ofStr(""));
//System.out.println("MD5(\"a\"):" + m.getMD5ofStr("a"));
//System.out.println("MD5(\"abc\"):" + m.getMD5ofStr("abc"));
//System.out.println("MD5(\"message digest\"):" +
// m.getMD5ofStr("message digest"));
//System.out.println("MD5(\"abcdefghijklmnopqrstuvwxyz\"):" +
// m.getMD5ofStr("abcdefghijklmnopqrstuvwxyz"));
//System.out.println(
// "MD5(\"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789\"):" +
// m.getMD5ofStr(
// "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"));
System.out.println(new Date().getTime());
long l = new Date().getTime();
long timestamp = new Date().getTime();
String strTS = String.valueOf(timestamp);
if(strTS != null && strTS.length()>10)
{
strTS = strTS.substring(0,10);
System.out.println(strTS);
}
System.out.println(m.getMD5ofStr("123"));
}
}
网友评论