Commit 38334d5a authored by Quxl's avatar Quxl
parents bcfe718f aa71e6cf
...@@ -15,7 +15,7 @@ import java.util.regex.Matcher; ...@@ -15,7 +15,7 @@ import java.util.regex.Matcher;
import java.util.regex.Pattern; import java.util.regex.Pattern;
public class DateUtil { public class DateUtil {
public static final String FMT_HH = "HH"; public static final String FMT_HH = "HH";
public static final String FMT_DATE_HH = "yyyy-MM-dd HH"; public static final String FMT_DATE_HH = "yyyy-MM-dd HH";
public static final String FMT_TIME = "HH:mm:ss"; public static final String FMT_TIME = "HH:mm:ss";
...@@ -31,43 +31,55 @@ public class DateUtil { ...@@ -31,43 +31,55 @@ public class DateUtil {
public static final String FMT_DATE_ISO = "yyyy-MM-ddTHH:mm:ss.SSSZ"; public static final String FMT_DATE_ISO = "yyyy-MM-ddTHH:mm:ss.SSSZ";
public static final String FMT_UTC_GMT = "EEE, dd MMM yyyy HH:mm:ss z"; public static final String FMT_UTC_GMT = "EEE, dd MMM yyyy HH:mm:ss z";
public static final String FMT_YYYYMMddHHMMSS = "yyyyMMddHHmmss"; public static final String FMT_YYYYMMddHHMMSS = "yyyyMMddHHmmss";
public static final String FMT_UTC_ALIYUN="YYYY-MM-DD'T'hh:mm:ss'Z'"; public static final String FMT_UTC_ALIYUN = "YYYY-MM-DD'T'hh:mm:ss'Z'";
public static final String FMT_YYYY_MM = "yyyy-MM"; public static final String FMT_YYYY_MM = "yyyy-MM";
public static final Long SECOND = 1000L; public static final Long SECOND = 1000L;
public static final Long MINUTE = 1000L*60; public static final Long MINUTE = 1000L * 60;
public static final Long HALF_HOUR = MINUTE*30; public static final Long HALF_HOUR = MINUTE * 30;
public static final Long HOUR = HALF_HOUR*2; public static final Long HOUR = HALF_HOUR * 2;
public static final Long HALF_DAY = HOUR*12; public static final Long HALF_DAY = HOUR * 12;
public static final Long DAY = HALF_DAY*2; public static final Long DAY = HALF_DAY * 2;
private static final Map<Pattern, String> PATTERN_DATE = new LinkedHashMap<Pattern, String>(); private static final Map<Pattern, String> PATTERN_DATE = new LinkedHashMap<Pattern, String>();
static { static {
PATTERN_DATE.put(Pattern.compile("(([1-2][0-9]{3})年(([0]?[1-9])|([1][0-2]))月(([0]?[1-9])|([1-2][0-9])|([3][0-1]))日\\s+\\d{1,2}时\\d{1,2}分\\d{1,2}秒)"), "yyyy年MM月dd日 HH时mm分ss秒"); PATTERN_DATE.put(Pattern.compile(
PATTERN_DATE.put(Pattern.compile("(([1-2][0-9]{3})年(([0]?[1-9])|([1][0-2]))月(([0]?[1-9])|([1-2][0-9])|([3][0-1]))日\\s+\\d{1,2}:\\d{1,2}:\\d{1,2})"), "yyyy年MM月dd日 HH:mm:ss"); "(([1-2][0-9]{3})年(([0]?[1-9])|([1][0-2]))月(([0]?[1-9])|([1-2][0-9])|([3][0-1]))日\\s+\\d{1,2}时\\d{1,2}分\\d{1,2}秒)"),
PATTERN_DATE.put(Pattern.compile("(([1-2][0-9]{3})年(([0]?[1-9])|([1][0-2]))月(([0]?[1-9])|([1-2][0-9])|([3][0-1]))日)"), "yyyy年MM月dd日"); "yyyy年MM月dd日 HH时mm分ss秒");
PATTERN_DATE.put(Pattern.compile(
"(([1-2][0-9]{3})年(([0]?[1-9])|([1][0-2]))月(([0]?[1-9])|([1-2][0-9])|([3][0-1]))日\\s+\\d{1,2}:\\d{1,2}:\\d{1,2})"),
"yyyy年MM月dd日 HH:mm:ss");
PATTERN_DATE.put(
Pattern.compile("(([1-2][0-9]{3})年(([0]?[1-9])|([1][0-2]))月(([0]?[1-9])|([1-2][0-9])|([3][0-1]))日)"),
"yyyy年MM月dd日");
PATTERN_DATE.put(Pattern.compile("(([1-2][0-9]{3})年(([0]?[1-9])|([1][0-2]))月)"), "yyyy年MM月"); PATTERN_DATE.put(Pattern.compile("(([1-2][0-9]{3})年(([0]?[1-9])|([1][0-2]))月)"), "yyyy年MM月");
PATTERN_DATE.put(Pattern.compile("(([1-2][0-9]{3})年)"), "yyyy年"); PATTERN_DATE.put(Pattern.compile("(([1-2][0-9]{3})年)"), "yyyy年");
PATTERN_DATE.put(Pattern.compile("(\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}.\\d{3}Z)"), DateUtil.FMT_DATE_ISO); PATTERN_DATE.put(Pattern.compile("(\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}.\\d{3}Z)"), DateUtil.FMT_DATE_ISO);
PATTERN_DATE.put(Pattern.compile("(\\d{4}/\\d{1,2}/\\d{1,2}\\s+\\d{1,2}:\\d{1,2}:\\d{1,2})"), DateUtil.FMT_A_DATE_SECOND); PATTERN_DATE.put(Pattern.compile("(\\d{4}/\\d{1,2}/\\d{1,2}\\s+\\d{1,2}:\\d{1,2}:\\d{1,2})"),
PATTERN_DATE.put(Pattern.compile("(\\d{4}/\\d{1,2}/\\d{1,2}\\s+\\d{1,2}:\\d{1,2})"), DateUtil.FMT_A_DATE_MINUTE); DateUtil.FMT_A_DATE_SECOND);
PATTERN_DATE.put(Pattern.compile("(\\d{4}/\\d{1,2}/\\d{1,2}\\s+\\d{1,2}:\\d{1,2})"),
DateUtil.FMT_A_DATE_MINUTE);
PATTERN_DATE.put(Pattern.compile("(\\d{4}/\\d{1,2}/\\d{1,2})"), DateUtil.FMT_A_DATE); PATTERN_DATE.put(Pattern.compile("(\\d{4}/\\d{1,2}/\\d{1,2})"), DateUtil.FMT_A_DATE);
PATTERN_DATE.put(Pattern.compile("(\\d{4}-\\d{1,2}-\\d{1,2}\\s+\\d{1,2}:\\d{1,2}:\\d{1,2})"), DateUtil.FMT_DATE_SECOND); PATTERN_DATE.put(Pattern.compile("(\\d{4}-\\d{1,2}-\\d{1,2}\\s+\\d{1,2}:\\d{1,2}:\\d{1,2})"),
DateUtil.FMT_DATE_SECOND);
PATTERN_DATE.put(Pattern.compile("(\\d{4}-\\d{1,2}-\\d{1,2}\\s+\\d{1,2}:\\d{1,2})"), DateUtil.FMT_DATE_MINUTE); PATTERN_DATE.put(Pattern.compile("(\\d{4}-\\d{1,2}-\\d{1,2}\\s+\\d{1,2}:\\d{1,2})"), DateUtil.FMT_DATE_MINUTE);
PATTERN_DATE.put(Pattern.compile("(\\d{4}-\\d{1,2}-\\d{1,2})"), DateUtil.FMT_DATE); PATTERN_DATE.put(Pattern.compile("(\\d{4}-\\d{1,2}-\\d{1,2})"), DateUtil.FMT_DATE);
PATTERN_DATE.put(Pattern.compile("(([1-2][0-9]{3})(([0][1-9])|([1][0-2]))(([0][1-9])|([1-2][0-9])|([3][0-1])))"), "yyyyMMdd"); PATTERN_DATE.put(
Pattern.compile("(([1-2][0-9]{3})(([0][1-9])|([1][0-2]))(([0][1-9])|([1-2][0-9])|([3][0-1])))"),
"yyyyMMdd");
PATTERN_DATE.put(Pattern.compile("(([1-2][0-9]{3})(([0][1-9])|([1][0-2])))"), "yyyyMM"); PATTERN_DATE.put(Pattern.compile("(([1-2][0-9]{3})(([0][1-9])|([1][0-2])))"), "yyyyMM");
PATTERN_DATE.put(Pattern.compile("([1-2][0-9]{3})"), "yyyy"); PATTERN_DATE.put(Pattern.compile("([1-2][0-9]{3})"), "yyyy");
} }
/** /**
* 将日期字符串转化成日期类型 * 将日期字符串转化成日期类型
*
* @param date * @param date
* @param fmt * @param fmt
* @return * @return
...@@ -82,23 +94,24 @@ public class DateUtil { ...@@ -82,23 +94,24 @@ public class DateUtil {
throw new RuntimeException(date + " parse to" + fmt, e); throw new RuntimeException(date + " parse to" + fmt, e);
} }
} }
/** /**
* 自动判断日期字符串格式并将其转化为日期类型 * 自动判断日期字符串格式并将其转化为日期类型
*
* @param str * @param str
* @return * @return
*/ */
public static Date parse(Object obj) { public static Date parse(Object obj) {
if(obj instanceof Date) { if (obj instanceof Date) {
return new Date(((Date)obj).getTime()); return new Date(((Date) obj).getTime());
} else { } else {
String str = String.valueOf(obj).trim(); String str = String.valueOf(obj).trim();
if(StringUtil.isNotEmpty(str)) { if (StringUtil.isNotEmpty(str)) {
for(Pattern pattern : PATTERN_DATE.keySet()) { for (Pattern pattern : PATTERN_DATE.keySet()) {
Matcher matcher = pattern.matcher(str); Matcher matcher = pattern.matcher(str);
if(matcher.find()) { if (matcher.find()) {
String date_str = matcher.group(1); String date_str = matcher.group(1);
if(PATTERN_DATE.get(pattern).equals(DateUtil.FMT_DATE_ISO)) { if (PATTERN_DATE.get(pattern).equals(DateUtil.FMT_DATE_ISO)) {
return parseISODate(date_str); return parseISODate(date_str);
} else { } else {
return parse(date_str, PATTERN_DATE.get(pattern)); return parse(date_str, PATTERN_DATE.get(pattern));
...@@ -109,27 +122,27 @@ public class DateUtil { ...@@ -109,27 +122,27 @@ public class DateUtil {
return null; return null;
} }
} }
public static Date parseISODate(String isoDate) { public static Date parseISODate(String isoDate) {
isoDate = isoDate.replace("T", " ").replace("Z", ""); isoDate = isoDate.replace("T", " ").replace("Z", "");
Date date = parse(isoDate); Date date = parse(isoDate);
java.util.Calendar cal = java.util.Calendar.getInstance(); java.util.Calendar cal = java.util.Calendar.getInstance();
cal.setTime(date); cal.setTime(date);
int zoneOffset = cal.get(java.util.Calendar.ZONE_OFFSET); int zoneOffset = cal.get(java.util.Calendar.ZONE_OFFSET);
int dstOffset = cal.get(java.util.Calendar.DST_OFFSET); int dstOffset = cal.get(java.util.Calendar.DST_OFFSET);
cal.add(Calendar.MILLISECOND, (zoneOffset + dstOffset)); cal.add(Calendar.MILLISECOND, (zoneOffset + dstOffset));
return cal.getTime(); return cal.getTime();
} }
public static boolean isDate(Object obj) { public static boolean isDate(Object obj) {
if(obj instanceof Date) { if (obj instanceof Date) {
return true; return true;
} else { } else {
String str = String.valueOf(obj); String str = String.valueOf(obj);
if(StringUtil.isNotEmpty(str)) { if (StringUtil.isNotEmpty(str)) {
String date_str = str.trim(); String date_str = str.trim();
for(Pattern pattern : PATTERN_DATE.keySet()) { for (Pattern pattern : PATTERN_DATE.keySet()) {
if(pattern.matcher(date_str).find()) { if (pattern.matcher(date_str).find()) {
return true; return true;
} }
} }
...@@ -137,33 +150,36 @@ public class DateUtil { ...@@ -137,33 +150,36 @@ public class DateUtil {
return false; return false;
} }
} }
/** /**
* 格式化日期为字符串 * 格式化日期为字符串
*
* @param date * @param date
* @param fmt * @param fmt
* @return * @return
*/ */
public static String format(Date date, String fmt) { public static String format(Date date, String fmt) {
if(date == null) { if (date == null) {
return null; return null;
} else { } else {
SimpleDateFormat sdf = new SimpleDateFormat(fmt); SimpleDateFormat sdf = new SimpleDateFormat(fmt);
return sdf.format(date); return sdf.format(date);
} }
} }
/** /**
* 格式化为yyyy-MM-dd格式 * 格式化为yyyy-MM-dd格式
* @param date 时间参数 *
* @param date 时间参数
* @return yyyy-MM-dd * @return yyyy-MM-dd
*/ */
public static String formatDate(Date date) { public static String formatDate(Date date) {
return format(date, DateUtil.FMT_DATE); return format(date, DateUtil.FMT_DATE);
} }
/** /**
* 格式化日期为yyyy-MM-dd HH:mm:ss格式 * 格式化日期为yyyy-MM-dd HH:mm:ss格式
*
* @param date * @param date
* @return yyyy-MM-dd HH:mm:ss * @return yyyy-MM-dd HH:mm:ss
*/ */
...@@ -171,27 +187,27 @@ public class DateUtil { ...@@ -171,27 +187,27 @@ public class DateUtil {
SimpleDateFormat sdf = new SimpleDateFormat(DateUtil.FMT_DATE_SECOND); SimpleDateFormat sdf = new SimpleDateFormat(DateUtil.FMT_DATE_SECOND);
return sdf.format(date); return sdf.format(date);
} }
public static String formatUTCDate(Date date) { public static String formatUTCDate(Date date) {
SimpleDateFormat dateFormat = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z", Locale.ENGLISH); SimpleDateFormat dateFormat = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z", Locale.ENGLISH);
dateFormat.setTimeZone(new SimpleTimeZone(0, "UTC")); dateFormat.setTimeZone(new SimpleTimeZone(0, "UTC"));
return dateFormat.format(date); return dateFormat.format(date);
} }
public static String formatGMTDate(Date date) { public static String formatGMTDate(Date date) {
SimpleDateFormat dateFormat = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z", Locale.ENGLISH); SimpleDateFormat dateFormat = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z", Locale.ENGLISH);
dateFormat.setTimeZone(new SimpleTimeZone(0, "GMT")); dateFormat.setTimeZone(new SimpleTimeZone(0, "GMT"));
return dateFormat.format(date); return dateFormat.format(date);
} }
/** /**
* 将毫秒数格式化成默认格式日期字符串 * 将毫秒数格式化成默认格式日期字符串 默认格式:yyyy-MM-dd HH:mm:ss
* 默认格式:yyyy-MM-dd HH:mm:ss *
* @param time * @param time
* @return * @return
*/ */
public static String format(Long time) { public static String format(Long time) {
if(time != null) { if (time != null) {
Date date = new Date(time); Date date = new Date(time);
SimpleDateFormat sdf = new SimpleDateFormat(DateUtil.FMT_DATE_SECOND); SimpleDateFormat sdf = new SimpleDateFormat(DateUtil.FMT_DATE_SECOND);
return sdf.format(date); return sdf.format(date);
...@@ -199,15 +215,16 @@ public class DateUtil { ...@@ -199,15 +215,16 @@ public class DateUtil {
return null; return null;
} }
} }
/** /**
* 将毫秒数格式化为制定格式的日期字符串 * 将毫秒数格式化为制定格式的日期字符串
*
* @param time * @param time
* @param fmt * @param fmt
* @return * @return
*/ */
public static String format(Long time, String fmt) { public static String format(Long time, String fmt) {
if(time != null) { if (time != null) {
Date date = new Date(time); Date date = new Date(time);
SimpleDateFormat sdf = new SimpleDateFormat(fmt); SimpleDateFormat sdf = new SimpleDateFormat(fmt);
return sdf.format(date); return sdf.format(date);
...@@ -217,26 +234,26 @@ public class DateUtil { ...@@ -217,26 +234,26 @@ public class DateUtil {
} }
/** /**
* 将毫秒数格式化为时间格式字符串 * 将毫秒数格式化为时间格式字符串 毫秒数必须小于86400000
* 毫秒数必须小于86400000 *
* @param time * @param time
* @return * @return
*/ */
public static String format(Integer time) { public static String format(Integer time) {
return format(time, DateUtil.FMT_TIME); return format(time, DateUtil.FMT_TIME);
} }
/** /**
* 将毫秒数格式化为时间格式字符串 * 将毫秒数格式化为时间格式字符串 毫秒数必须小于86400000
* 毫秒数必须小于86400000 *
* @param time * @param time
* @param fmt * @param fmt
* @return * @return
*/ */
public static String format(Integer time, String fmt) { public static String format(Integer time, String fmt) {
if(time != null) { if (time != null) {
if(time < 86400000) { if (time < 86400000) {
Date date = new Date(time - (1000*60*60*8)); Date date = new Date(time - (1000 * 60 * 60 * 8));
SimpleDateFormat sdf = new SimpleDateFormat(fmt); SimpleDateFormat sdf = new SimpleDateFormat(fmt);
return sdf.format(date); return sdf.format(date);
} else { } else {
...@@ -246,9 +263,10 @@ public class DateUtil { ...@@ -246,9 +263,10 @@ public class DateUtil {
return null; return null;
} }
} }
/** /**
* 计算指定时间当天的开始时间 * 计算指定时间当天的开始时间
*
* @param time * @param time
* @return * @return
* @throws ParseException * @throws ParseException
...@@ -257,59 +275,64 @@ public class DateUtil { ...@@ -257,59 +275,64 @@ public class DateUtil {
Long start = start(time == null ? new Date() : time).getTime(); Long start = start(time == null ? new Date() : time).getTime();
return new Date(start + HALF_DAY); return new Date(start + HALF_DAY);
} }
/** /**
* 计算指定时间当天的开始时间 * 计算指定时间当天的开始时间
*
* @param time * @param time
* @return * @return
* @throws ParseException * @throws ParseException
*/ */
public static Date start(Date time) { public static Date start(Date time) {
if(time != null) { if (time != null) {
return parse(format(time, DateUtil.FMT_DATE), DateUtil.FMT_DATE); return parse(format(time, DateUtil.FMT_DATE), DateUtil.FMT_DATE);
} else { } else {
return null; return null;
} }
} }
/** /**
* 计算指定日期当天的最后时间 * 计算指定日期当天的最后时间
*
* @param time * @param time
* @return * @return
* @throws ParseException * @throws ParseException
*/ */
public static Date end(Date time) { public static Date end(Date time) {
if(time != null) { if (time != null) {
return new Date(start(new Date(time.getTime() + (24L*60L*60L*1000L))).getTime()); return new Date(start(new Date(time.getTime() + (24L * 60L * 60L * 1000L))).getTime());
} else { } else {
return null; return null;
} }
} }
/** /**
* 取得当前时间向后或向前若干天的时间 * 取得当前时间向后或向前若干天的时间
*
* @param time * @param time
* @param offset * @param offset
* @return * @return
*/ */
public static Date day(Date time, Integer offset) { public static Date day(Date time, Integer offset) {
Date date = new Date(time.getTime() + (offset*86400000L)); Date date = new Date(time.getTime() + (offset * 86400000L));
return date; return date;
} }
/** /**
* 计算指定的日期是星期几,返回数字 周日至周六分别是0-6 * 计算指定的日期是星期几,返回数字 周日至周六分别是0-6
*
* @param date * @param date
* @return * @return
*/ */
public static Integer week(Date date) { public static Integer week(Date date) {
Calendar calendar = Calendar.getInstance(); Calendar calendar = Calendar.getInstance();
calendar.setTime(date); calendar.setTime(date);
return calendar.get(Calendar.DAY_OF_WEEK) - 1; return calendar.get(Calendar.DAY_OF_WEEK) - 1;
} }
/** /**
* 计算两天之间相隔多少天 * 计算两天之间相隔多少天
*
* @param start * @param start
* @param end * @param end
* @return * @return
...@@ -317,11 +340,12 @@ public class DateUtil { ...@@ -317,11 +340,12 @@ public class DateUtil {
public static Integer days(Date start, Date end) { public static Integer days(Date start, Date end) {
Date date_start = start(start); Date date_start = start(start);
Date date_end = start(end); Date date_end = start(end);
return (int)((date_end.getTime() - date_start.getTime()) / 86400000L); return (int) ((date_end.getTime() - date_start.getTime()) / 86400000L);
} }
/** /**
* 判断是否是今天 * 判断是否是今天
*
* @param date * @param date
* @return * @return
*/ */
...@@ -329,87 +353,93 @@ public class DateUtil { ...@@ -329,87 +353,93 @@ public class DateUtil {
Date today = new Date(); Date today = new Date();
Date start = start(today); Date start = start(today);
Date end = end(today); Date end = end(today);
if(date.getTime() >= start.getTime() && date.getTime() < end.getTime()) { if (date.getTime() >= start.getTime() && date.getTime() < end.getTime()) {
return true; return true;
} else { } else {
return false; return false;
} }
} }
/** /**
* 取得当前日期是多少周 * 取得当前日期是多少周
* @param date *
* @return * @param date
*/ * @return
*/
public static int getWeekOfYear(Date date) { public static int getWeekOfYear(Date date) {
Calendar c = new GregorianCalendar(); Calendar c = new GregorianCalendar();
c.setFirstDayOfWeek(Calendar.MONDAY); c.setFirstDayOfWeek(Calendar.MONDAY);
c.setMinimalDaysInFirstWeek(7); c.setMinimalDaysInFirstWeek(7);
c.setTime (date); c.setTime(date);
return c.get(Calendar.WEEK_OF_YEAR); return c.get(Calendar.WEEK_OF_YEAR);
} }
/** /**
* 得到某一年周的总数 * 得到某一年周的总数
* @param year *
* @return * @param year
*/ * @return
public static int getMaxWeekNumOfYear(int year) { */
public static int getMaxWeekNumOfYear(int year) {
Calendar c = new GregorianCalendar(); Calendar c = new GregorianCalendar();
c.set(year, Calendar.DECEMBER, 31, 23, 59, 59); c.set(year, Calendar.DECEMBER, 31, 23, 59, 59);
return getWeekOfYear(c.getTime()); return getWeekOfYear(c.getTime());
} }
/** /**
* 得到某年某周的第一天 * 得到某年某周的第一天
* @param year *
* @param week * @param year
* @return * @param week
*/ * @return
*/
public static Date getFirstDayOfWeek(int year, int week) { public static Date getFirstDayOfWeek(int year, int week) {
Calendar c = new GregorianCalendar(); Calendar c = new GregorianCalendar();
c.set(Calendar.YEAR, year); c.set(Calendar.YEAR, year);
c.set (Calendar.MONTH, Calendar.JANUARY); c.set(Calendar.MONTH, Calendar.JANUARY);
c.set(Calendar.DATE, 1); c.set(Calendar.DATE, 1);
Calendar cal = (GregorianCalendar) c.clone(); Calendar cal = (GregorianCalendar) c.clone();
cal.add(Calendar.DATE, week * 7); cal.add(Calendar.DATE, week * 7);
return getFirstDayOfWeek(cal.getTime ()); return getFirstDayOfWeek(cal.getTime());
} }
/** /**
* 得到某年某周的最后一天 * 得到某年某周的最后一天
* @param year *
* @param week * @param year
* @return * @param week
*/ * @return
*/
public static Date getLastDayOfWeek(int year, int week) { public static Date getLastDayOfWeek(int year, int week) {
Calendar c = new GregorianCalendar(); Calendar c = new GregorianCalendar();
c.set(Calendar.YEAR, year); c.set(Calendar.YEAR, year);
c.set(Calendar.MONTH, Calendar.JANUARY); c.set(Calendar.MONTH, Calendar.JANUARY);
c.set(Calendar.DATE, 1); c.set(Calendar.DATE, 1);
Calendar cal = (GregorianCalendar) c.clone(); Calendar cal = (GregorianCalendar) c.clone();
cal.add(Calendar.DATE , week * 7); cal.add(Calendar.DATE, week * 7);
return getLastDayOfWeek(cal.getTime()); return getLastDayOfWeek(cal.getTime());
} }
/** /**
* 取得当前日期所在周的第一天 * 取得当前日期所在周的第一天
* @param date *
* @return * @param date
*/ * @return
public static Date getFirstDayOfWeek(Date date) { */
public static Date getFirstDayOfWeek(Date date) {
Calendar c = new GregorianCalendar(); Calendar c = new GregorianCalendar();
c.setFirstDayOfWeek(Calendar.MONDAY); c.setFirstDayOfWeek(Calendar.MONDAY);
c.setTime(date); c.setTime(date);
c.set(Calendar.DAY_OF_WEEK, c.getFirstDayOfWeek()); // Monday c.set(Calendar.DAY_OF_WEEK, c.getFirstDayOfWeek()); // Monday
return c.getTime (); return c.getTime();
} }
/** /**
* 取得当前日期所在周的最后一天 * 取得当前日期所在周的最后一天
* @param date *
* @return * @param date
*/ * @return
*/
public static Date getLastDayOfWeek(Date date) { public static Date getLastDayOfWeek(Date date) {
Calendar c = new GregorianCalendar(); Calendar c = new GregorianCalendar();
c.setFirstDayOfWeek(Calendar.MONDAY); c.setFirstDayOfWeek(Calendar.MONDAY);
...@@ -417,67 +447,70 @@ public class DateUtil { ...@@ -417,67 +447,70 @@ public class DateUtil {
c.set(Calendar.DAY_OF_WEEK, c.getFirstDayOfWeek() + 6); c.set(Calendar.DAY_OF_WEEK, c.getFirstDayOfWeek() + 6);
return c.getTime(); return c.getTime();
} }
/** /**
* 取得当前日期所在月的第一天 * 取得当前日期所在月的第一天
*
* @param date * @param date
* @return * @return
*/ */
public static Date getFirstDayOfMonth(Date date){ public static Date getFirstDayOfMonth(Date date) {
Calendar c = Calendar.getInstance(); Calendar c = Calendar.getInstance();
c.add(Calendar.MONTH, 0); c.add(Calendar.MONTH, 0);
c.set(Calendar.DAY_OF_MONTH,1);//设置为1号,当前日期既为本月第一天 c.set(Calendar.DAY_OF_MONTH, 1);// 设置为1号,当前日期既为本月第一天
return c.getTime(); return c.getTime();
} }
/**
 * 获取指定日期下个月的第一天 的日期 /**
* @param dateStr *
* @param format *  * 获取指定日期下个月的第一天 的日期
* @return *
*/ * @param dateStr
public static String getFirstDayOfNextMonth(String dateStr,String format){ * @param format
* @return
*/
public static String getFirstDayOfNextMonth(String dateStr, String format) {
SimpleDateFormat sdf = new SimpleDateFormat(format); SimpleDateFormat sdf = new SimpleDateFormat(format);
try { try {
Date date = sdf.parse(dateStr); Date date = sdf.parse(dateStr);
Calendar calendar = Calendar.getInstance(); Calendar calendar = Calendar.getInstance();
calendar.setTime(date); calendar.setTime(date);
calendar.set(Calendar.DAY_OF_MONTH,1); calendar.set(Calendar.DAY_OF_MONTH, 1);
calendar.add(Calendar.MONTH, 1); calendar.add(Calendar.MONTH, 1);
return sdf.format(calendar.getTime()); return sdf.format(calendar.getTime());
} catch (ParseException e) { } catch (ParseException e) {
e.printStackTrace(); e.printStackTrace();
} }
return null; return null;
} }
public static String getLastMonth(String format,int month) { public static String getLastMonth(String format, int month) {
try { try {
SimpleDateFormat sdf = new SimpleDateFormat(format); SimpleDateFormat sdf = new SimpleDateFormat(format);
//获取前一个月第一天 // 获取前一个月第一天
Calendar calendar1 = Calendar.getInstance(); Calendar calendar1 = Calendar.getInstance();
calendar1.add(Calendar.MONTH, month); calendar1.add(Calendar.MONTH, month);
calendar1.set(Calendar.DAY_OF_MONTH,1); calendar1.set(Calendar.DAY_OF_MONTH, 1);
return sdf.format(calendar1.getTime()); return sdf.format(calendar1.getTime());
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
} }
return null; return null;
} }
public static String getTimeStamp() { public static String getTimeStamp() {
return String.valueOf(System.currentTimeMillis() / 1000); return String.valueOf(System.currentTimeMillis() / 1000);
} }
/** /**
* 获取指定小时前的日期 * 获取指定小时前的日期
*/ */
public static String beforeHourDay(String fmt,int hour) { public static String beforeHourDay(String fmt, int hour) {
Calendar calendar = Calendar.getInstance(); Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, calendar.get(Calendar.HOUR_OF_DAY) - hour); calendar.set(Calendar.HOUR_OF_DAY, calendar.get(Calendar.HOUR_OF_DAY) - hour);
return format(calendar.getTime(), fmt); return format(calendar.getTime(), fmt);
} }
/** /**
* 取得当前时间向后或向前若干天的时间 * 取得当前时间向后或向前若干天的时间
* *
...@@ -489,7 +522,7 @@ public class DateUtil { ...@@ -489,7 +522,7 @@ public class DateUtil {
Date date = new Date(new Date().getTime() + (offset * 86400000L)); Date date = new Date(new Date().getTime() + (offset * 86400000L));
return format(date, fmt); return format(date, fmt);
} }
/** /**
* 获取两个日期字符串之间的日期集合 * 获取两个日期字符串之间的日期集合
* @param startTime:String * @param startTime:String
...@@ -521,6 +554,26 @@ public class DateUtil { ...@@ -521,6 +554,26 @@ public class DateUtil {
e.printStackTrace(); e.printStackTrace();
} }
return list; return list;
} }
/**
* 时间加8小时,时区问题
* <p>Title: </p>
* <p>Description: </p>
* @param time
* @return
*/
public static String formatTimeEight(String time) {
String newTime = time;
try {
SimpleDateFormat sdf = new SimpleDateFormat(FMT_DATE_SECOND);
Date d = sdf.parse(time);
long rightTime = (long) (d.getTime() + 8 *60 * 60 * 1000);
newTime = sdf.format(rightTime);
} catch (ParseException e) {
e.printStackTrace();
}
return newTime;
}
} }
package com.egolm.common; package com.egolm.common;
import java.io.ByteArrayOutputStream; import java.io.ByteArrayOutputStream;
import java.io.File; import java.io.File;
import java.io.FileInputStream; import java.io.FileInputStream;
import java.io.IOException; import java.io.IOException;
import java.io.OutputStream; import java.io.OutputStream;
import java.io.UnsupportedEncodingException; import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection; import java.net.HttpURLConnection;
import java.net.Proxy; import java.net.Proxy;
import java.net.URL; import java.net.URL;
import java.net.URLEncoder; import java.net.URLEncoder;
import java.security.cert.CertificateException; import java.security.cert.CertificateException;
import java.security.cert.X509Certificate; import java.security.cert.X509Certificate;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.HashMap; import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.regex.Matcher; import java.util.regex.Matcher;
import java.util.regex.Pattern; import java.util.regex.Pattern;
import javax.net.ssl.HttpsURLConnection; import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext; import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager; import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager; import javax.net.ssl.X509TrustManager;
import com.egolm.common.exception.HttpRequestException; import com.egolm.common.exception.HttpRequestException;
import com.egolm.common.exception.HttpResponseException; import com.egolm.common.exception.HttpResponseException;
import com.egolm.common.exception.HttpUrlEncodingException; import com.egolm.common.exception.HttpUrlEncodingException;
/** /**
* *
* @author 曲欣亮 * @author 曲欣亮
* @since 2015-04-01 * @since 2015-04-01
* *
*/ */
public class HttpUtil { public class HttpUtil {
static { static {
System.setProperty("sun.net.http.allowRestrictedHeaders", "true"); System.setProperty("sun.net.http.allowRestrictedHeaders", "true");
} }
private static final String charset = "utf-8"; private static final String charset = "utf-8";
private static SSLContext sslContextDefault = null; private static SSLContext sslContextDefault = null;
private static class TrustAnyTrustManager implements X509TrustManager { private static class TrustAnyTrustManager implements X509TrustManager {
public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException { public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
} }
public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException { public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
} }
public X509Certificate[] getAcceptedIssuers() { public X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[] {}; return new X509Certificate[] {};
} }
} }
private static SSLContext getDefaultSSLContext() { private static SSLContext getDefaultSSLContext() {
if (sslContextDefault == null) { if (sslContextDefault == null) {
try { try {
sslContextDefault = SSLContext.getInstance("SSL"); sslContextDefault = SSLContext.getInstance("SSL");
sslContextDefault.init(null, new TrustManager[] { new TrustAnyTrustManager() }, new java.security.SecureRandom()); sslContextDefault.init(null, new TrustManager[] { new TrustAnyTrustManager() }, new java.security.SecureRandom());
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
} }
} }
return sslContextDefault; return sslContextDefault;
} }
private static HttpURLConnection createConnection(String requestUrl, Proxy proxy) throws IOException{ private static HttpURLConnection createConnection(String requestUrl, Proxy proxy) throws IOException{
URL HTTP_URL = new URL(requestUrl); URL HTTP_URL = new URL(requestUrl);
HttpURLConnection connection = (HttpURLConnection) (proxy == null ? HTTP_URL.openConnection() : HTTP_URL.openConnection(proxy)); HttpURLConnection connection = (HttpURLConnection) (proxy == null ? HTTP_URL.openConnection() : HTTP_URL.openConnection(proxy));
if (requestUrl.startsWith("https")) { if (requestUrl.startsWith("https")) {
((HttpsURLConnection) connection).setSSLSocketFactory(getDefaultSSLContext().getSocketFactory()); ((HttpsURLConnection) connection).setSSLSocketFactory(getDefaultSSLContext().getSocketFactory());
} }
return connection; return connection;
} }
public static String get(String requestUrl) throws HttpRequestException { public static String get(String requestUrl) throws HttpRequestException {
return HttpUtil.get(requestUrl, null, null, null); return HttpUtil.get(requestUrl, null, null, null);
} }
public static String get(String requestUrl, Map<?, ?> parameters) throws HttpRequestException { public static String get(String requestUrl, Map<?, ?> parameters) throws HttpRequestException {
return HttpUtil.get(requestUrl, parameters, null, null); return HttpUtil.get(requestUrl, parameters, null, null);
} }
public static String get(String requestUrl, Map<?, ?> parameters, Map<String, String> header) public static String get(String requestUrl, Map<?, ?> parameters, Map<String, String> header)
throws HttpRequestException { throws HttpRequestException {
return HttpUtil.get(requestUrl, parameters, header, null); return HttpUtil.get(requestUrl, parameters, header, null);
} }
public static String get(String requestUrl, Map<?, ?> parameters, Map<String, String> header, Proxy proxy) public static String get(String requestUrl, Map<?, ?> parameters, Map<String, String> header, Proxy proxy)
throws HttpRequestException { throws HttpRequestException {
HttpURLConnection connection = null; HttpURLConnection connection = null;
try { try {
if (requestUrl.startsWith("https")) { if (requestUrl.startsWith("https")) {
} }
String requestBody = HttpUtil.toQueryString(parameters, charset); String requestBody = HttpUtil.toQueryString(parameters, charset);
requestUrl = requestUrl + (requestUrl.contains("?") ? (requestUrl.endsWith("&") ? "" : "&") : "?") requestUrl = requestUrl + (requestUrl.contains("?") ? (requestUrl.endsWith("&") ? "" : "&") : "?")
+ requestBody; + requestBody;
System.out.println(requestUrl); System.out.println(requestUrl);
connection = createConnection(requestUrl, proxy); connection = createConnection(requestUrl, proxy);
connection.setRequestMethod("GET"); connection.setRequestMethod("GET");
connection.setRequestProperty("Accept-Charset", charset); connection.setRequestProperty("Accept-Charset", charset);
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
if (header != null) { if (header != null) {
for (String key : header.keySet()) { for (String key : header.keySet()) {
connection.setRequestProperty(key, header.get(key)); connection.setRequestProperty(key, header.get(key));
} }
} }
connection.connect(); connection.connect();
return responseBody(connection); return responseBody(connection);
} catch (Exception e) { } catch (Exception e) {
throw new HttpRequestException("HTTP(GET)请求异常", e); throw new HttpRequestException("HTTP(GET)请求异常", e);
} finally { } finally {
connection.disconnect(); connection.disconnect();
} }
} }
public static String post(String requestUrl) throws HttpRequestException { public static String post(String requestUrl) throws HttpRequestException {
return HttpUtil.post(requestUrl, null); return HttpUtil.post(requestUrl, null);
} }
public static String post(String requestUrl, Map<?, ?> parameters) throws HttpRequestException { public static String post(String requestUrl, Map<?, ?> parameters) throws HttpRequestException {
return HttpUtil.post(requestUrl, parameters, null); return HttpUtil.post(requestUrl, parameters, null);
} }
public static String post(String requestUrl, Map<?, ?> parameters, Map<String, String> headers) public static String post(String requestUrl, Map<?, ?> parameters, Map<String, String> headers)
throws HttpRequestException { throws HttpRequestException {
return HttpUtil.post(requestUrl, parameters, headers, null); return HttpUtil.post(requestUrl, parameters, headers, null);
} }
public static String post(String requestUrl, Map<?, ?> parameters, Map<String, String> headers, Proxy proxy) public static String post(String requestUrl, Map<?, ?> parameters, Map<String, String> headers, Proxy proxy)
throws HttpRequestException { throws HttpRequestException {
return post(requestUrl, HttpUtil.toQueryString(parameters, charset), headers, proxy); return post(requestUrl, HttpUtil.toQueryString(parameters, charset), headers, proxy);
} }
public static String post(String requestUrl, String text, Map<String, String> headers, Proxy proxy) public static String post(String requestUrl, String text, Map<String, String> headers, Proxy proxy)
throws HttpRequestException { throws HttpRequestException {
HttpURLConnection connection = null; HttpURLConnection connection = null;
try { try {
byte[] bytes = text == null ? new byte[0] : text.getBytes(); byte[] bytes = text == null ? new byte[0] : text.getBytes();
connection = createConnection(requestUrl, proxy); connection = createConnection(requestUrl, proxy);
connection.setDoOutput(true); connection.setDoOutput(true);
connection.setDoInput(true); connection.setDoInput(true);
connection.setRequestMethod("POST"); connection.setRequestMethod("POST");
connection.setUseCaches(false); connection.setUseCaches(false);
connection.setInstanceFollowRedirects(true); connection.setInstanceFollowRedirects(true);
connection.setRequestProperty("Accept-Charset", charset); connection.setRequestProperty("Accept-Charset", charset);
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.setRequestProperty("Content-Length", String.valueOf(bytes.length)); connection.setRequestProperty("Content-Length", String.valueOf(bytes.length));
if (headers != null) { if (headers != null) {
for (String key : headers.keySet()) { for (String key : headers.keySet()) {
connection.setRequestProperty(key, headers.get(key)); connection.setRequestProperty(key, headers.get(key));
} }
} }
OutputStream out = connection.getOutputStream(); OutputStream out = connection.getOutputStream();
out.write(bytes); out.write(bytes);
out.close(); out.close();
return responseBody(connection); return responseBody(connection);
} catch (Exception e) { } catch (Exception e) {
throw new HttpRequestException("HTTP(POST)请求异常", e); throw new HttpRequestException("HTTP(POST)请求异常", e);
} finally { } finally {
connection.disconnect(); connection.disconnect();
} }
} }
private static final Pattern pattern = Pattern.compile("charset(\\s+)?=(\\s+)?([0-9a-zA-Z\\-]+)"); private static final Pattern pattern = Pattern.compile("charset(\\s+)?=(\\s+)?([0-9a-zA-Z\\-]+)");
public static String responseBody(HttpURLConnection connection) throws HttpResponseException { public static String responseBody(HttpURLConnection connection) throws HttpResponseException {
try { try {
byte[] bytes; byte[] bytes;
try { try {
bytes = FileUtil.streamToBytes(connection.getInputStream()); bytes = FileUtil.streamToBytes(connection.getInputStream());
} catch (IOException e) { } catch (IOException e) {
bytes = FileUtil.streamToBytes(connection.getErrorStream()); bytes = FileUtil.streamToBytes(connection.getErrorStream());
} }
Map<String, List<String>> responseHeaders = connection.getHeaderFields(); Map<String, List<String>> responseHeaders = connection.getHeaderFields();
List<String> contentTypes = responseHeaders.get("Content-Type"); List<String> contentTypes = responseHeaders.get("Content-Type");
String responseCharsetName = null; String responseCharsetName = null;
if (contentTypes != null) { if (contentTypes != null) {
for (String contentType : contentTypes) { for (String contentType : contentTypes) {
Matcher matcher = pattern.matcher(contentType); Matcher matcher = pattern.matcher(contentType);
if (matcher.find()) { if (matcher.find()) {
responseCharsetName = matcher.group(3); responseCharsetName = matcher.group(3);
break; break;
} }
} }
} }
if (responseCharsetName == null || responseCharsetName.trim().length() == 0) { if (responseCharsetName == null || responseCharsetName.trim().length() == 0) {
return new String(bytes, charset); return new String(bytes, charset);
} else { } else {
return new String(bytes, responseCharsetName); return new String(bytes, responseCharsetName);
} }
} catch (Exception e) { } catch (Exception e) {
throw new HttpResponseException("获取HTTP请求响应结果异常", e); throw new HttpResponseException("获取HTTP请求响应结果异常", e);
} }
} }
public static Map<String, String[]> toParameters(String queryString) { public static Map<String, String[]> toParameters(String queryString) {
Map<String, List<String>> map = new HashMap<String, List<String>>(); Map<String, List<String>> map = new HashMap<String, List<String>>();
String[] ary = queryString.split("&"); String[] ary = queryString.split("&");
for (String str : ary) { for (String str : ary) {
if (StringUtil.isNotEmpty(str)) { if (StringUtil.isNotEmpty(str)) {
String[] kv = str.split("=", 2); String[] kv = str.split("=", 2);
List<String> list = map.get(kv[0]); List<String> list = map.get(kv[0]);
if (list == null) { if (list == null) {
list = new ArrayList<String>(); list = new ArrayList<String>();
} }
list.add(StringUtil.isNotBlank(kv[1]) ? kv[1] : null); list.add(StringUtil.isNotBlank(kv[1]) ? kv[1] : null);
map.put(kv[0], list); map.put(kv[0], list);
} }
} }
Map<String, String[]> params = new HashMap<String, String[]>(); Map<String, String[]> params = new HashMap<String, String[]>();
for (String key : map.keySet()) { for (String key : map.keySet()) {
List<String> list = map.get(key); List<String> list = map.get(key);
params.put(key, list.toArray(new String[list.size()])); params.put(key, list.toArray(new String[list.size()]));
} }
return params; return params;
} }
public static String toQueryString(Map<?, ?> parameters) { public static String toQueryString(Map<?, ?> parameters) {
return toQueryString(parameters, null); return toQueryString(parameters, null);
} }
public static String toQueryString(Map<?, ?> parameters, String encode) throws HttpUrlEncodingException { public static String toQueryString(Map<?, ?> parameters, String encode) throws HttpUrlEncodingException {
try { try {
List<String> params = new ArrayList<String>(); List<String> params = new ArrayList<String>();
if (parameters != null) { if (parameters != null) {
for (Object key : parameters.keySet()) { for (Object key : parameters.keySet()) {
Object val = parameters.get(key); Object val = parameters.get(key);
String sKey = String.valueOf(key); String sKey = String.valueOf(key);
Object[] sVals = (val == null ? null Object[] sVals = (val == null ? null
: (val instanceof Object[] ? (Object[]) val : new Object[] { val })); : (val instanceof Object[] ? (Object[]) val : new Object[] { val }));
if (sVals != null && sVals.length > 0) { if (sVals != null && sVals.length > 0) {
for (Object sVal : sVals) { for (Object sVal : sVals) {
params.add(sKey + "=" + (sVal == null ? "" params.add(sKey + "=" + (sVal == null ? ""
: URLEncoder.encode(String.valueOf(sVal), encode == null ? charset : encode))); : URLEncoder.encode(String.valueOf(sVal), encode == null ? charset : encode)));
} }
} else { } else {
params.add("sKey="); params.add("sKey=");
} }
} }
} }
return StringUtil.join("&", params); return StringUtil.join("&", params);
} catch (UnsupportedEncodingException e) { } catch (UnsupportedEncodingException e) {
throw new HttpUrlEncodingException("URL编码异常", e); throw new HttpUrlEncodingException("URL编码异常", e);
} }
} }
public static String formatToQueryString(Map<?, ?> parameters) { public static String formatToQueryString(Map<?, ?> parameters) {
List<String> params = new ArrayList<String>(); List<String> params = new ArrayList<String>();
if (parameters != null) { if (parameters != null) {
for (Object key : parameters.keySet()) { for (Object key : parameters.keySet()) {
Object val = parameters.get(key); Object val = parameters.get(key);
String sKey = String.valueOf(key); String sKey = String.valueOf(key);
Object[] sVals = (val == null ? null Object[] sVals = (val == null ? null
: (val instanceof Object[] ? (Object[]) val : new Object[] { val })); : (val instanceof Object[] ? (Object[]) val : new Object[] { val }));
if (sVals != null && sVals.length > 0) { if (sVals != null && sVals.length > 0) {
for (Object sVal : sVals) { for (Object sVal : sVals) {
params.add(sKey + "=" + (sVal == null ? "" : sVal)); if(StringUtil.isNotEmpty(sVal)) {
} params.add(sKey + "=" +sVal);
} else { }
params.add(sKey + "="); }
} }
} /*else {
} params.add(sKey + "="); 空值不参与签名
return StringUtil.join("&", params); }*/
} }
}
public static String post(String requestUrl, Map<String, Object> parameters, Map<String, String> headers, return StringUtil.join("&", params);
Map<String, File> attachments, String contentType) { }
HttpURLConnection connection = null;
try { public static String post(String requestUrl, Map<String, Object> parameters, Map<String, String> headers,
Data data = new Data(); Map<String, File> attachments, String contentType) {
String BOUNDARY = "----WebKitFormBoundaryT1HoybnYeFOGFlBR"; HttpURLConnection connection = null;
StringBuffer ParamBuffer = new StringBuffer(); try {
if (parameters != null) { Data data = new Data();
for (String key : parameters.keySet()) { String BOUNDARY = "----WebKitFormBoundaryT1HoybnYeFOGFlBR";
ParamBuffer.append("--" + BOUNDARY + "\r\n"); StringBuffer ParamBuffer = new StringBuffer();
ParamBuffer.append("Content-Disposition: form-data; name=\"" + key + "\"\r\n"); if (parameters != null) {
ParamBuffer.append("\r\n"); for (String key : parameters.keySet()) {
ParamBuffer.append(parameters.get(key) + "\r\n"); ParamBuffer.append("--" + BOUNDARY + "\r\n");
} ParamBuffer.append("Content-Disposition: form-data; name=\"" + key + "\"\r\n");
} ParamBuffer.append("\r\n");
String ParamBufferString = ParamBuffer.toString(); ParamBuffer.append(parameters.get(key) + "\r\n");
data.add(ParamBufferString.getBytes()); }
if (attachments != null) { }
for (String name : attachments.keySet()) { String ParamBufferString = ParamBuffer.toString();
StringBuffer FileBuffer = new StringBuffer(); data.add(ParamBufferString.getBytes());
File file = attachments.get(name); if (attachments != null) {
FileBuffer.append("--" + BOUNDARY + "\r\n"); for (String name : attachments.keySet()) {
FileBuffer.append("Content-Disposition: form-data; name=\"" + name + "\"; filename=\"" StringBuffer FileBuffer = new StringBuffer();
+ file.getName() + "\"" + "\r\n"); File file = attachments.get(name);
FileBuffer.append("Content-Type:" + contentType + "" + "\r\n"); FileBuffer.append("--" + BOUNDARY + "\r\n");
FileBuffer.append("\r\n"); FileBuffer.append("Content-Disposition: form-data; name=\"" + name + "\"; filename=\""
String FileBufferString = FileBuffer.toString(); + file.getName() + "\"" + "\r\n");
data.add(FileBufferString.getBytes()); FileBuffer.append("Content-Type:" + contentType + "" + "\r\n");
data.add(file); FileBuffer.append("\r\n");
String FileEnd = "\r\n"; String FileBufferString = FileBuffer.toString();
data.add(FileEnd.getBytes()); data.add(FileBufferString.getBytes());
} data.add(file);
} String FileEnd = "\r\n";
StringBuffer EndBuffer = new StringBuffer("\r\n--" + BOUNDARY + "--\r\n"); data.add(FileEnd.getBytes());
String EndBufferString = EndBuffer.toString(); }
data.add(EndBufferString.getBytes()); }
connection = createConnection(requestUrl, null); StringBuffer EndBuffer = new StringBuffer("\r\n--" + BOUNDARY + "--\r\n");
connection.setRequestMethod("POST"); String EndBufferString = EndBuffer.toString();
connection.setRequestProperty("Accept-Charset", "utf-8"); data.add(EndBufferString.getBytes());
connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY); connection = createConnection(requestUrl, null);
connection.setRequestProperty("Content-Length", String.valueOf(data.length())); connection.setRequestMethod("POST");
if (headers != null) { connection.setRequestProperty("Accept-Charset", "utf-8");
for (String key : headers.keySet()) { connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY);
connection.setRequestProperty(key, headers.get(key)); connection.setRequestProperty("Content-Length", String.valueOf(data.length()));
} if (headers != null) {
} for (String key : headers.keySet()) {
connection.setDoOutput(true); connection.setRequestProperty(key, headers.get(key));
OutputStream out = connection.getOutputStream(); }
out.write(data.bytes()); }
out.close(); connection.setDoOutput(true);
return responseBody(connection); OutputStream out = connection.getOutputStream();
} catch (Exception e) { out.write(data.bytes());
throw new RuntimeException(e); out.close();
} finally { return responseBody(connection);
connection.disconnect(); } catch (Exception e) {
} throw new RuntimeException(e);
} } finally {
connection.disconnect();
static class Data { }
}
private byte[][] ds = new byte[0][0];
static class Data {
public void add(File file) throws IOException {
FileInputStream fis = new FileInputStream(file); private byte[][] ds = new byte[0][0];
ByteArrayOutputStream bos = new ByteArrayOutputStream(1000);
byte[] b = new byte[1000]; public void add(File file) throws IOException {
int n; FileInputStream fis = new FileInputStream(file);
while ((n = fis.read(b)) != -1) { ByteArrayOutputStream bos = new ByteArrayOutputStream(1000);
bos.write(b, 0, n); byte[] b = new byte[1000];
} int n;
fis.close(); while ((n = fis.read(b)) != -1) {
bos.close(); bos.write(b, 0, n);
add(bos.toByteArray()); }
} fis.close();
bos.close();
public void add(byte[] data) { add(bos.toByteArray());
int length = ds.length; }
byte[][] ds_tmp = new byte[length + 1][];
for (int i = 0; i < length; i++) { public void add(byte[] data) {
ds_tmp[i] = ds[i]; int length = ds.length;
} byte[][] ds_tmp = new byte[length + 1][];
ds_tmp[length] = data; for (int i = 0; i < length; i++) {
ds = ds_tmp; ds_tmp[i] = ds[i];
} }
ds_tmp[length] = data;
public int length() { ds = ds_tmp;
int length = 0; }
for (byte[] b : ds) {
length += b.length; public int length() {
} int length = 0;
return length; for (byte[] b : ds) {
} length += b.length;
}
public byte[] bytes() { return length;
byte[] bytes = new byte[length()]; }
int index = 0;
for (int i = 0; i < ds.length; i++) { public byte[] bytes() {
for (int k = 0; k < ds[i].length; k++) { byte[] bytes = new byte[length()];
bytes[index++] = ds[i][k]; int index = 0;
} for (int i = 0; i < ds.length; i++) {
} for (int k = 0; k < ds[i].length; k++) {
return bytes; bytes[index++] = ds[i][k];
} }
} }
return bytes;
} }
}
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment