常用工具類整理
阿新 • • 發佈:2018-12-20
本文旨在整理個人工作總結,僅供參考
- HttpClientUtil工具類原始碼:
import java.io.IOException;
import java.util.Date;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
/**
* @ClassName: HttpClientUtil
* @Description: HTTP-POST請求工具類
* @author sly.shuai
* @date2017年7月6日 上午10:29:20
* @version V1.0
*/
public class HttpClientUtil
{
/**
* @Title: doHttpRequest
* @Description: 傳送http請求
* @param apiURL
* @param sendParam
* @return String
* @throws
* @變更記錄 2017年7月18日 下午2:48:01 sly.shuai 建立
*/
public static String doHttpRequest(String apiURL, String sendParam) {
DefaultHttpClient httpClient = new DefaultHttpClient();// httpClient
HttpPost post = new HttpPost(apiURL); // POST請求
StringEntity entity = null;
HttpResponse response = null;
String responseContent = null; // 響應內容
try {
entity = new StringEntity(sendParam, "UTF-8"); // 防止中文亂碼
entity.setContentEncoding("UTF-8");
post.setHeader("Content-Type", "application/json"); // 設定請求頭
post.setEntity(entity);
// 從響應值中取得token
response = httpClient.execute(post);
// 返回狀態碼為200時處理結果
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
HttpEntity httpEntity = response.getEntity();
responseContent = EntityUtils.toString(httpEntity, "UTF-8");
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
httpClient.getConnectionManager().shutdown();
}
return responseContent;
}
/**
* @Title: doHttpsRequest
* @Description: 傳送https請求
* @param apiURL
* @param sendParam
* @return String
* @throws
* @變更記錄 2017年7月18日 下午2:47:36 sly.shuai 建立
*/
public static String doHttpsRequest(String apiURL, String sendParam) {
HttpClient httpClient = null;// httpClient
HttpPost post = new HttpPost(apiURL); // POST請求
StringEntity entity = null;
HttpResponse response = null;
String responseContent = null; // 響應內容
try {
httpClient = new SSLClient();
entity = new StringEntity(sendParam, "UTF-8"); // 防止中文亂碼
entity.setContentEncoding("UTF-8");
post.setHeader("Content-Type", "application/json"); // 設定請求頭
post.setEntity(entity);
// 從響應值中取得token
response = httpClient.execute(post);
// 返回狀態碼為200時處理結果
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
HttpEntity httpEntity = response.getEntity();
responseContent = EntityUtils.toString(httpEntity, "UTF-8");
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
} finally {
httpClient.getConnectionManager().shutdown();
}
return responseContent;
}
}
上面所引用到的SSLClient類原始碼:
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import org.apache.http.conn.ClientConnectionManager;
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.impl.client.DefaultHttpClient;
/**
* @ClassName: SSLClient
* @Description:SSLClient
* @author sly.shuai
* @date2017年7月18日 上午11:37:02
* @version V1.0
*/
public class SSLClient extends DefaultHttpClient
{
public SSLClient() throws Exception {
super();
SSLContext ctx = SSLContext.getInstance("TLS");
X509TrustManager tm = new X509TrustManager() {
public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {}
public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {}
public X509Certificate[] getAcceptedIssuers() {
return null;
}
};
ctx.init(null, new TrustManager[] { tm }, null);
// 允許所有證書
SSLSocketFactory ssf = new SSLSocketFactory(ctx, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
ClientConnectionManager ccm = this.getConnectionManager();
SchemeRegistry sr = ccm.getSchemeRegistry();
sr.register(new Scheme("https", 443, ssf));
}
}
- 資料劃分原始碼:
import java.util.List;
import java.util.Map;
/**
* @ClassName: DataPartition
* @Description:
* @author sly.shuai
* @date2017年7月24日 上午11:12:43
* @version V1.0
*/
@SuppressWarnings("rawtypes")
public class DataPartitionUtil
{
/**
* @Title: partitioningData
* @Description: 劃分資料
* @param list
* void
* @throws
* @變更記錄 2017年7月24日 上午11:35:37 sly.shuai 建立
*/
public static void partitioningData(List<Map> list) {
if (list != null && list.size() > 0) {
int total = list.size();// 總數
int avg = 10;// 每10條傳送一次
int number = total / avg;// 傳送次數
int remainder = total % avg;// 餘數
int index = 0;// 索引
// 如果餘數大於0則增加一次傳送次數
if (remainder > 0) {
number = number + 1;
}
if (number > 0) {
for (int i = 0; i < number; i++) {
if (index + avg > total) {
List<Map> sonList = list.subList(avg * i, total);
// 這裡處理最後剩下的數量不超過10的資料
} else {
List<Map> sonList = list.subList(avg * i, avg * i + avg);
// 這裡處理劃分的每10條資料
index += avg;
}
}
}
}
}
}
- 計算時間之差原始碼:
import java.util.Date;
/**
* @ClassName: DateDiffer
* @Description:
* @author sly.shuai
* @date2017年7月24日 上午11:38:51
* @version V1.0
*/
public class DateDiffer
{
/**
* @Title: getDistanceTimes
* @Description: 計算時間之差
* @param now
* @param old
* @return long[]
* @throws
* @變更記錄 2017年7月7日 上午11:38:16 sly.shuai 建立
*/
public static long[] getDistanceTimes(Date now, Date old) {
long nd = 1000 * 24 * 60 * 60;// 一天的毫秒數
long nh = 1000 * 60 * 60;// 一小時的毫秒數
long nm = 1000 * 60;// 一分鐘的毫秒數
long ns = 1000;// 一秒鐘的毫秒數
long diff;
long day = 0l;
long hour = 0l;
long min = 0l;
long sec = 0l;
try {
// 獲得兩個時間的毫秒時間差異
diff = now.getTime() - old.getTime();
day = diff / nd;// 計算差多少天
hour = diff % nd / nh;// 計算差多少小時
min = diff % nd % nh / nm;// 計算差多少分鐘
sec = diff % nd % nh % nm / ns;// 計算差多少秒
} catch (Exception e) {
e.printStackTrace();
}
long[] times = { day, hour, min, sec };
return times;
}
}