Linux安全网 - Linux操作系统_Linux 命令_Linux教程_Linux黑客

绿色网站无广告
会员投稿 投稿指南 本期推荐:
搜索:
您的位置: Linux安全网 > Linux集群 > Architecture > » 正文

淘宝网的HttpClient工具

来源: liufei.fir 分享至:
package com.taobao.pegasus.common.utils; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.UnsupportedEncodingException; import java.util.ArrayList; import java.util.List; import java.util.Map; import org.apache.commons.httpclient.params.HttpClientParams; import org.apache.commons.io.IOUtils; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.HttpStatus; import org.apache.http.HttpVersion; import org.apache.http.NameValuePair; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.HttpClient; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.conn.ClientConnectionManager; import org.apache.http.conn.params.ConnManagerParams; import org.apache.http.conn.scheme.PlainSocketFactory; import org.apache.http.conn.scheme.Scheme; import org.apache.http.conn.scheme.SchemeRegistry; import org.apache.http.conn.ssl.SSLSocketFactory; import org.apache.http.entity.mime.MultipartEntity; import org.apache.http.entity.mime.content.FileBody; import org.apache.http.entity.mime.content.StringBody; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager; import org.apache.http.message.BasicNameValuePair; import org.apache.http.params.BasicHttpParams; import org.apache.http.params.HttpParams; import org.apache.http.params.HttpProtocolParams; /** * * @author cenpeng.lwm * */ public class HttpClientUtil { private static HttpParams params; private static ClientConnectionManager cm; static { params = new BasicHttpParams(); params.setParameter(HttpClientParams.SO_TIMEOUT, new Integer(500)); ConnManagerParams.setTimeout(params, 1000); ConnManagerParams.setMaxTotalConnections(params, 100); HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); SchemeRegistry schemeRegistry = new SchemeRegistry(); schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80)); schemeRegistry.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443)); cm = new ThreadSafeClientConnManager(params, schemeRegistry); } public static HttpClient getHttpclient() { return new DefaultHttpClient(cm, params); } public static boolean doStatusGet(String url) throws ClientProtocolException, IOException { HttpClient httpclient = new DefaultHttpClient(cm, params); HttpGet httpget = new HttpGet(url); HttpResponse res = httpclient.execute(httpget); return res.getStatusLine().getStatusCode() == HttpStatus.SC_OK; } public static InputStream doGet(String url) throws ClientProtocolException, IOException { HttpClient httpclient = new DefaultHttpClient(cm, params); HttpGet httpget = new HttpGet(url); HttpResponse res = httpclient.execute(httpget); InputStream in = null; if (res.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { in = res.getEntity().getContent(); } else { httpget.abort(); } return in; } public static InputStream doPost(String url, Map<String, String> m, String encoding) throws ClientProtocolException, IOException { HttpClient httpclient = new DefaultHttpClient(cm, params); HttpPost httpost = new HttpPost(url); httpost.setEntity(new UrlEncodedFormEntity(getNameValuePair(m), encoding)); HttpResponse res = httpclient.execute(httpost); InputStream in = null; ; if (res.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { in = res.getEntity().getContent(); } else { httpost.abort(); } return in; } public static InputStream doPost(String url, Map<String, String> m) throws ClientProtocolException, IOException { HttpClient httpclient = new DefaultHttpClient(cm, params); HttpPost httpost = new HttpPost(url); httpost.setEntity(new UrlEncodedFormEntity(getNameValuePair(m))); HttpResponse res = httpclient.execute(httpost); InputStream in = null; if (res.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { in = res.getEntity().getContent(); } else { httpost.abort(); } return in; } public static InputStream doPost(String url, Map<String, String> m, File file) throws ClientProtocolException, IOException { HttpClient httpclient = new DefaultHttpClient(cm, params); HttpPost httpost = new HttpPost(url); MultipartEntity reqEntity = new MultipartEntity(); FileBody fileBody = new FileBody(file); reqEntity.addPart("fileBody", fileBody); getNameValuePair(reqEntity, m); httpost.setEntity(reqEntity); HttpResponse res = httpclient.execute(httpost); InputStream in = null; if (res.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { HttpEntity resEntity = res.getEntity(); if (resEntity != null) { in = resEntity.getContent(); } } else { httpost.abort(); } return in; } public static String post(String url, Map<String, String> m, String paramEncoding, String encoding) throws ClientProtocolException, IOException { return toString(doPost(url, m, paramEncoding), encoding); } public static String post(String url, Map<String, String> m, String paramEncoding) throws ClientProtocolException, IOException { return toString(doPost(url, m, paramEncoding)); } public static String post(String url, Map<String, String> m) throws ClientProtocolException, IOException { return toString(doPost(url, m)); } public static String post(String url, Map<String, String> m, File file) throws ClientProtocolException, IOException { return toString(doPost(url, m, file)); } public static String get(String url, String encoding) throws ClientProtocolException, IOException { return toString(doGet(url), encoding); } public static String get(String url) throws ClientProtocolException, IOException { return toString(doGet(url)); } public static String toString(InputStream is, String encoding) throws IOException { String content = null; try { if (is != null) { content = IOUtils.toString(is, encoding); } } catch (IOException e) { throw e; } finally { if (is != null) { is.close(); } } return content; } public static String toString(InputStream is) throws IOException { String content = null; try { if (is != null) { content = IOUtils.toString(is); } } catch (IOException e) { throw e; } finally { if (is != null) { is.close(); } } return content; } public static List<NameValuePair> getNameValuePair(Map<String, String> m) { List<NameValuePair> list = new ArrayList<NameValuePair>(); for (String k : m.keySet()) { NameValuePair v = new BasicNameValuePair(k, m.get(k)); list.add(v); } return list; } public static void getNameValuePair(MultipartEntity reqEntity, Map<String, String> m) throws UnsupportedEncodingException { StringBody comment = null; for (String k : m.keySet()) { comment = new StringBody(m.get(k)); reqEntity.addPart(k, comment); } } public static void main(String[] s) throws ClientProtocolException, IOException { String sss = get("http://google.com"); System.out.print(sss); } }

时间工具
package com.taobao.pegasus.common.utils; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.Locale; import java.util.TimeZone; import org.apache.commons.lang.time.FastDateFormat; /** * * Title:<br> * Description:<br> * Author: CaMel <[email protected]><br> */ public class TimeUtil { /** * 2009-12-08 14:52:50 */ public static final String DEFAULT_DATETIME_FORMAT = "yyyy-MM-dd HH:mm:ss"; /** * 2009-12-08T14:52:50 */ public static final String ISO_DATETIME_FORMAT = "yyyy-MM-dd'T'HH:mm:ss"; /** * 2009-12-08T14:52:50+08:00 */ public static final String ISO_DATETIME_TIME_ZONE_FORMAT = "yyyy-MM-dd'T'HH:mm:ssZZ"; /** * 2009-12-08 */ public static final String ISO_DATE_FORMAT = "yyyy-MM-dd"; /** * 2009-12-08+08:00 */ public static final String ISO_DATE_TIME_ZONE_FORMAT = "yyyy-MM-ddZZ"; /** * T14:52:50 */ public static final String ISO_TIME_FORMAT = "'T'HH:mm:ss"; /** * T14:52:50+08:00 */ public static final String ISO_TIME_TIME_ZONE_FORMAT = "'T'HH:mm:ssZZ"; /** * 14:52:50 */ public static final String ISO_TIME_NO_T_FORMAT = "HH:mm:ss"; /** * 14:52:50+08:00 */ public static final String ISO_TIME_NO_T_TIME_ZONE_FORMAT = "HH:mm:ssZZ"; /** * 星期二, 08 十二月 2009 14:52:50 +0800 */ public static final String SMTP_DATETIME_FORMAT = "EEE, dd MMM yyyy HH:mm:ss Z"; public static String format(long millis, String pattern) { return format(new Date(millis), pattern, null, null); } public static String format(Date date, String pattern) { return format(date, pattern, null, null); } public static String format(Calendar calendar, String pattern) { return format(calendar, pattern, null, null); } public static String format(long millis, String pattern, TimeZone timeZone) { return format(new Date(millis), pattern, timeZone, null); } public static String format(Date date, String pattern, TimeZone timeZone) { return format(date, pattern, timeZone, null); } public static String format(Calendar calendar, String pattern, TimeZone timeZone) { return format(calendar, pattern, timeZone, null); } public static String format(long millis, String pattern, Locale locale) { return format(new Date(millis), pattern, null, locale); } public static String format(Date date, String pattern, Locale locale) { return format(date, pattern, null, locale); } public static String format(Calendar calendar, String pattern, Locale locale) { return format(calendar, pattern, null, locale); } public static String format(long millis, String pattern, TimeZone timeZone, Locale locale) { return format(new Date(millis), pattern, timeZone, locale); } public static String format(Date date, String pattern, TimeZone timeZone, Locale locale) { FastDateFormat df = FastDateFormat.getInstance(pattern, timeZone, locale); return df.format(date); } public static String format(Calendar calendar, String pattern, TimeZone timeZone, Locale locale) { FastDateFormat df = FastDateFormat.getInstance(pattern, timeZone, locale); return df.format(calendar); } public static Date parse(String date, String pattern) throws ParseException { SimpleDateFormat sf = new SimpleDateFormat(pattern); return sf.parse(date); } public static Date getEndOfDay(Date day) { Calendar cal = Calendar.getInstance(); cal.setTime(day); cal.set(Calendar.HOUR_OF_DAY, cal.getMaximum(Calendar.HOUR_OF_DAY)); cal.set(Calendar.MINUTE, cal.getMaximum(Calendar.MINUTE)); cal.set(Calendar.SECOND, cal.getMaximum(Calendar.SECOND)); cal.set(Calendar.MILLISECOND, cal.getMaximum(Calendar.MILLISECOND)); return cal.getTime(); } public static Date getStartOfDay(Date day) { Calendar cal = Calendar.getInstance(); cal.setTime(day); cal.set(Calendar.HOUR_OF_DAY, cal.getMinimum(Calendar.HOUR_OF_DAY)); cal.set(Calendar.MINUTE, cal.getMinimum(Calendar.MINUTE)); cal.set(Calendar.SECOND, cal.getMinimum(Calendar.SECOND)); cal.set(Calendar.MILLISECOND, cal.getMinimum(Calendar.MILLISECOND)); return cal.getTime(); } public static Date getNoonOfDay(Date day) { Calendar cal = Calendar.getInstance(); cal.setTime(day); cal.set(Calendar.HOUR_OF_DAY, 12); cal.set(Calendar.MINUTE, cal.getMinimum(Calendar.MINUTE)); cal.set(Calendar.SECOND, cal.getMinimum(Calendar.SECOND)); cal.set(Calendar.MILLISECOND, cal.getMinimum(Calendar.MILLISECOND)); return cal.getTime(); } public static Date getStartOfMonth(Date day) { Calendar cal = Calendar.getInstance(); cal.setTime(day); cal.set(Calendar.DAY_OF_MONTH, cal.getMinimum(Calendar.DAY_OF_MONTH)); cal.set(Calendar.HOUR_OF_DAY, cal.getMinimum(Calendar.HOUR_OF_DAY)); cal.set(Calendar.MINUTE, cal.getMinimum(Calendar.MINUTE)); cal.set(Calendar.SECOND, cal.getMinimum(Calendar.SECOND)); cal.set(Calendar.MILLISECOND, cal.getMinimum(Calendar.MILLISECOND)); return cal.getTime(); } public static Date getEndOfMonth(Date day) { Calendar cal = Calendar.getInstance(); cal.setTime(day); cal.set(Calendar.DAY_OF_MONTH, cal.getActualMaximum(Calendar.DAY_OF_MONTH)); cal.set(Calendar.HOUR_OF_DAY, cal.getMaximum(Calendar.HOUR_OF_DAY)); cal.set(Calendar.MINUTE, cal.getMaximum(Calendar.MINUTE)); cal.set(Calendar.SECOND, cal.getMaximum(Calendar.SECOND)); cal.set(Calendar.MILLISECOND, cal.getMaximum(Calendar.MILLISECOND)); return cal.getTime(); } /** * 返回小时:分:秒 * * @param second * @return */ public static String getTimeString(int second) { int HOUR = 60 * 60; // int t = 6036; int h = second / HOUR; int m = (second % HOUR) / 60; int s = second % 60; return addZero(h) + ":" + addZero(m) + ":" + addZero(s); } public static String timeIntToString(int seconds) { StringBuffer result = new StringBuffer(""); if (seconds > 3600) { // hour:min:sec int hour = seconds / 3600; int min = (seconds - hour * 3600) / 60; int sec = seconds - hour * 3600 - min * 60; if (hour < 10) { result.append("0").append(hour); } else { result.append(hour); } result.append(":"); if (min < 10) { result.append("0").append(min); } else { result.append(min); } result.append(":"); if (sec < 10) { result.append("0").append(sec); } else { result.append(sec); } } else if (seconds > 0) { int min = seconds / 60; int sec = seconds - min * 60; if (min < 10) { result.append("0").append(min); } else { result.append(min); } result.append(":"); if (sec < 10) { result.append("0").append(sec); } else { result.append(sec); } } else { result = new StringBuffer("-1"); } return result.toString(); } public static String getFriendlyTimeDiff(Date now) { return getFriendlyTimeDiff(now.getTime(), System.currentTimeMillis()); } public static String getFriendlyTimeDiff(long time, long timeNow) { long diff = timeNow - time; String str = ""; if (diff > 0) { long s = diff / (60 * 1000); long h = s / 60; long d = h / 24; long m = d / 30; long y = m / 12; if (y > 0) { str = y + "年前"; } else if (m > 0) { str = m + "月前"; } else if (d > 0) { str = d + "天前"; } else if (h > 0) { str = h + "小时前"; } else if (s > 0) { str = s + "分钟前"; } else { str = "刚刚"; } } return str; } public static final String addZero(int i) { return i < 10 ? "0" + i : "" + i; } public static String calcHMS(long timeInSeconds) { long hours, minutes, seconds; timeInSeconds = timeInSeconds / 1000; hours = timeInSeconds / 3600; timeInSeconds = timeInSeconds - (hours * 3600); minutes = timeInSeconds / 60; timeInSeconds = timeInSeconds - (minutes * 60); seconds = timeInSeconds; return hours + " hour(s) " + minutes + " minute(s) " + seconds + " second(s)"; } /** * 是否超时 * * @param standard * 基准 * @param d2 * 比较时间 * @return */ public static boolean isTimeout(long standard, long d2, int delaySecond) { if (standard - d2 > delaySecond * 1000) { return true; } else { return false; } } public static void main(String[] args) throws ParseException { Date d1 = TimeUtil.parse("2011-05-05 14:33:30", "yyyy-MM-dd HH:mm:ss"); Date d2 = TimeUtil.parse("2011-05-05 14:30:24", "yyyy-MM-dd HH:mm:ss"); System.out.println(isTimeout(d1.getTime(), d2.getTime(), 3 * 60)); } }

Tags:
分享至:
最新图文资讯
1 2 3 4 5 6
验证码:点击我更换图片 理智评论文明上网,拒绝恶意谩骂 用户名:
关于我们 - 联系我们 - 广告服务 - 友情链接 - 网站地图 - 版权声明 - 发展历史