Commit d899d4ff authored by Java-范 志勇's avatar Java-范 志勇

修改代码

parent e16407d2
......@@ -12,17 +12,25 @@ import cn.gq.financial.model.bill.UMPayBill;
import cn.gq.financial.model.bill.WXBill;
import cn.gq.financial.model.bill.YeepayBill;
import java.util.concurrent.TimeUnit;
public class RepayFinancialAPP {
private static final Logger LOGGER = LoggerFactory.getLogger(RepayFinancialAPP.class);
static final String CONFIG_LOCAL="applicationContext.xml";
static final String CONFIG_LOCAL = "applicationContext.xml";
static Integer month = 8;
static String SRC_BILL_PATH ="E:\\易宝白条-9月";
// static String SRC_BILL_PATH ="E:\\WX_BILL\\GBK";
static String payAprroach="易宝";
// static String SRC_BILL_PATH = "E:\\financial-system-data\\weichat\\baitiao"; //微信白条
// static String SRC_BILL_PATH = "E:\\financial-system-data\\weichat\\xianjindai"; //微信现金贷
// static String SRC_BILL_PATH = "E:\\financial-system-data\\umpay\\baitiao"; //联动优势白条
// static String SRC_BILL_PATH = "E:\\financial-system-data\\umpay\\xianjindai"; //联动优势现金贷
static String SRC_BILL_PATH = "E:\\financial-system-data\\yeepay\\xianjindai"; //易宝现金贷
static String payAprroach = "易宝";
static String payAccount = "易宝-白条账户";
static String payAccount = "易宝-现金贷账户";
private static ClassPathXmlApplicationContext context = null;
......@@ -43,19 +51,24 @@ public class RepayFinancialAPP {
}
public static void main(String[] args) throws Exception {
LOGGER.info("======开始处理还款账单======");
long begin = System.currentTimeMillis();
RepayHandler handler = getSpringContext().getBean(RepayHandler.class);
//按照参数,对账
handler.repayBillDetailHandler(SRC_BILL_PATH, clazz, payAccount, month);
FinancialRepayDetailService repayDetailService = getSpringContext().getBean(FinancialRepayDetailService.class);
if (Constants.result.size() != 0) {
repayDetailService.saveDetails(Constants.result);
try {
LOGGER.info("======开始处理还款账单======");
long begin = System.currentTimeMillis();
RepayHandler handler = getSpringContext().getBean(RepayHandler.class);
//按照参数,对账
handler.repayBillDetailHandler(SRC_BILL_PATH, clazz, payAccount, month + 1);
FinancialRepayDetailService repayDetailService = getSpringContext().getBean(FinancialRepayDetailService.class);
if (Constants.result.size() != 0) {
repayDetailService.saveDetails(Constants.result);
}
LOGGER.info("总还款明细数量-->{}", Constants.result.size());
LOGGER.info("======结束处理还款账单======");
LOGGER.info("总计耗时--->{}mm", (System.currentTimeMillis() - begin));
} catch (Exception ex) {
ex.printStackTrace();
} finally {
context.close();
}
LOGGER.info("总还款明细数量-->{}",Constants.result.size());
context.close();
LOGGER.info("======结束处理还款账单======");
LOGGER.info("总计耗时--->{}mm", (System.currentTimeMillis() - begin));
}
public static ClassPathXmlApplicationContext getSpringContext() {
......
......@@ -13,6 +13,7 @@ import cn.gq.financial.service.FinancialRepayDetailService;
import cn.gq.financial.utils.Constants;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Component;
......@@ -27,7 +28,7 @@ public class RepayHandler {
static int ITEM_SIZE = 10000;
@Autowired
private ThreadPoolTaskExecutor threadPoolTaskExecutor;
private ThreadPoolTaskExecutor threadPoolTaskExecutor;
@Autowired
private PaycenterService paycenterService;
@Autowired
......@@ -42,13 +43,7 @@ public class RepayHandler {
private CountDownLatch count = null;
public void repayBillDetailHandler(final String srcPaht,final Class<? extends Bill> clazz, String payAccount, Integer month) throws Exception {
// List<Bill> bills = getBillsFromFile(srcPaht,clazz,payAccount,month);
List<Bill> bills = new ArrayList<>();
YeepayBill bill = new YeepayBill();
bill.setOrderId("1469787374013");
bill.setIncome(new BigDecimal("830.04"));
bill.setBizType(YeepayBill.REPAY);
bills.add(bill);
List<Bill> bills = getBillsFromFile(srcPaht,clazz,payAccount,month);
if(!CollectionUtils.isEmpty(bills)){
asyncHandlerRepayData(clazz, bills);
count.await(); //等待所有线程结束
......
......@@ -5,6 +5,7 @@ import cn.gq.financial.model.db.RepayDetailFinancial;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;
......@@ -67,9 +68,14 @@ public class FinancialRepayDetailService {
@Override
public void run() {
int succCount = repayDetailMapper.insert(records);
latch.countDown();
LOGGER.info("待插入记录数为{}条, 成功插入{}条", records.size(), succCount);
try {
int succCount = repayDetailMapper.insert(records);
LOGGER.info("待插入记录数为{}条, 成功插入{}条", records.size(), succCount);
} catch (Exception ex) {
ex.printStackTrace();
} finally {
latch.countDown();
}
}
}
}
package cn.gq.financial.utils;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import cn.gq.financial.model.bill.UMPayBill;
import cn.gq.financial.model.bill.WXBill;
import cn.gq.financial.model.bill.YeepayBill;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import java.io.*;
import java.math.BigDecimal;
import java.nio.charset.Charset;
import java.text.ParseException;
......@@ -13,35 +18,25 @@ import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import cn.gq.financial.model.bill.UMPayBill;
import cn.gq.financial.model.bill.WXBill;
import cn.gq.financial.model.bill.YeepayBill;
public class BillParsers {
static String PARSE_PATTERN_1 = "yyyy-MM-dd HH:mm:ss";
static String PARSE_PATTERN_2 = "yyyyMMdd";
public class BillParsers {
static String PARSE_PATTERN_1="yyyy-MM-dd HH:mm:ss";
static String PARSE_PATTERN_2="yyyyMMdd";
public static <T> List<T> parseBillFromInputStream(File file,Class<T> clazz) throws Exception{
return parseBillFromInputStream(new FileInputStream(file),clazz);
public static <T> List<T> parseBillFromInputStream(File file, Class<T> clazz) throws Exception {
return parseBillFromInputStream(new FileInputStream(file), clazz);
}
@SuppressWarnings("unchecked")
public static <T> List<T> parseBillFromInputStream(InputStream inputStream,Class<T> clazz) throws Exception{
if(clazz.equals(YeepayBill.class)){
return (List<T>) parseBillYeepayFromInputStream(inputStream);
public static <T> List<T> parseBillFromInputStream(InputStream inputStream, Class<T> clazz) throws Exception {
if (clazz.equals(YeepayBill.class)) {
return (List<T>) parseBillYeepay(inputStream);
}
if(clazz.equals(WXBill.class)){
if (clazz.equals(WXBill.class)) {
return (List<T>) parseBillWXPayFromInputStream(inputStream);
}
if(clazz.equals(UMPayBill.class)){
if (clazz.equals(UMPayBill.class)) {
return (List<T>) parseBillUMPayFromInputStream(inputStream);
}
throw new IllegalArgumentException("未知的第三方对账单类型,请核实");
......@@ -49,6 +44,7 @@ public class BillParsers {
/**
* 解析联动优势的账单
*
* @param inputStream
* @return
* @throws Exception
......@@ -57,17 +53,17 @@ public class BillParsers {
BufferedReader reader = null;
List<UMPayBill> bills = new ArrayList<UMPayBill>();
try {
reader = new BufferedReader(new InputStreamReader(inputStream));
reader = new BufferedReader(new InputStreamReader(inputStream));
String line = reader.readLine();
while(StringUtils.isNoneBlank(line = reader.readLine())){
if(line.startsWith("TRADEDETAIL-END")) break;
while (StringUtils.isNoneBlank(line = reader.readLine())) {
if (line.startsWith("TRADEDETAIL-END")) break;
UMPayBill bill = createUMPayBill(line);
bills.add(bill);
}
} catch (Exception e) {
throw e;
} finally{
if(null != reader){
} finally {
if (null != reader) {
try {
reader.close();
} catch (IOException e) {
......@@ -92,6 +88,7 @@ public class BillParsers {
/**
* 解析微信的账单
*
* @param inputStream
* @return
* @throws Exception
......@@ -101,22 +98,22 @@ public class BillParsers {
List<WXBill> bills = new ArrayList<WXBill>();
try {
reader = new BufferedReader(new InputStreamReader(inputStream, Charset.forName("UTF-8")));
String line = reader.readLine(); //越过第一行,同时判断该日是否有账单
if(line.startsWith("<xml>")) return bills;
while(StringUtils.isNoneBlank(line = reader.readLine())){
if(line.startsWith("总交易单数")) break; //账单条目结束
String line = reader.readLine(); //越过第一行,同时判断该日是否有账单
if (line.startsWith("<xml>")) return bills;
while (StringUtils.isNoneBlank(line = reader.readLine())) {
if (line.startsWith("总交易单数")) break; //账单条目结束
String[] split = line.split(",");
if("SUCCESS".equals(split[9])){
if ("SUCCESS".equals(split[9])) {
WXBill bill = createWXBill(split);
bills.add(bill);
}
}
} catch (Exception e) {
throw e;
} finally{
if(null != reader) {
} finally {
if (null != reader) {
try {
reader.close();
} catch (IOException e) {
......@@ -130,30 +127,74 @@ public class BillParsers {
private static WXBill createWXBill(String[] split) throws Exception {
WXBill bill = new WXBill();
bill.setOrderId(split[6].trim());
if(StringUtils.isNotBlank(split[12])){
if (StringUtils.isNotBlank(split[12])) {
bill.setIncome(new BigDecimal(split[12]));
}
if(StringUtils.isNoneBlank(split[22])){
if (StringUtils.isNoneBlank(split[22])) {
bill.setPoundage(new BigDecimal(split[22]));
}
bill.setTrandingDate(DateUtils.parseDate(split[0], PARSE_PATTERN_1));
bill.setWxOrderId(split[5]);
bill.setWxBizAccount(split[2]);
bill.setPubWXAccount(split[1]);
if(split[23].endsWith("%")){
String str = split[23].substring(0, split[23].length()-1);
if (split[23].endsWith("%")) {
String str = split[23].substring(0, split[23].length() - 1);
BigDecimal rate = new BigDecimal(str).divide(BigDecimal.TEN).divide(BigDecimal.TEN);
bill.setRate(rate);
}
return bill;
}
private static YeepayBill setYeePayBillProps(String[] contents) throws ParseException {
YeepayBill yeepayBill = new YeepayBill();
if (contents == null || contents.length == 0) {
throw new IllegalArgumentException("Invalid contents: " + StringUtils.join(contents, ","));
}
yeepayBill.setTradingDate(DateUtils.parseDate(contents[1], "yyyy-MM-dd HH:mm:ss.SSS"));
yeepayBill.setAccountType(contents[2]);
yeepayBill.setBizType(contents[3]);
if (StringUtils.isNotBlank(contents[4])) {
yeepayBill.setOrderId(contents[4]);
}
if (StringUtils.isNotBlank(contents[5])) {
yeepayBill.setIncome(new BigDecimal(contents[5]));
}
if (StringUtils.isNotBlank(contents[6])) {
yeepayBill.setCost(new BigDecimal(contents[6]));
}
if (StringUtils.isNotBlank(contents[7])) {
yeepayBill.setPoundage(new BigDecimal(contents[7]));
}
return yeepayBill;
}
private static List<YeepayBill> parseBillYeepay(InputStream is) throws Exception {
BufferedReader reader = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")));
String lineContent = reader.readLine();
String[] split;
List<YeepayBill> bills = new ArrayList<>();
int flag = 0;
while (StringUtils.isNotBlank(lineContent)) {
if (flag > 0) {
split = StringUtils.splitPreserveAllTokens(lineContent, ",");
YeepayBill bill = setYeePayBillProps(split);
bills.add(bill);
}
lineContent = reader.readLine();
flag++;
}
return bills;
}
;
/**
* 解析易宝的账单文件
*
* @param inputStream
* @return
* @throws IOException
* @throws IOException
*/
private static List<YeepayBill> parseBillYeepayFromInputStream(InputStream inputStream) throws IOException {
XSSFWorkbook workBook;
......@@ -161,8 +202,8 @@ public class BillParsers {
workBook = new XSSFWorkbook(inputStream);
XSSFSheet sheet = workBook.getSheetAt(0);
Iterator<Row> iterator = sheet.iterator();
iterator.next(); //跳过表头
while(iterator.hasNext()){
iterator.next(); //跳过表头
while (iterator.hasNext()) {
YeepayBill bill = createYeepayBill(iterator.next());
bills.add(bill);
}
......@@ -174,29 +215,28 @@ public class BillParsers {
bill.setTradingDate(row.getCell(1).getDateCellValue());
bill.setAccountType(row.getCell(2).getStringCellValue());
bill.setBizType(row.getCell(3).getStringCellValue());
if(StringUtils.isNotBlank(row.getCell(4).getStringCellValue())){
if (StringUtils.isNotBlank(row.getCell(4).getStringCellValue())) {
bill.setOrderId(row.getCell(4).getStringCellValue().trim());
}
row.getCell(5).setCellType(Cell.CELL_TYPE_STRING);
if(StringUtils.isNotBlank(row.getCell(5).getStringCellValue())){
if (StringUtils.isNotBlank(row.getCell(5).getStringCellValue())) {
bill.setIncome(new BigDecimal(row.getCell(5).getStringCellValue()));
}
row.getCell(6).setCellType(Cell.CELL_TYPE_STRING);
if(StringUtils.isNotBlank(row.getCell(6).getStringCellValue())){
if (StringUtils.isNotBlank(row.getCell(6).getStringCellValue())) {
bill.setCost(new BigDecimal(row.getCell(6).getStringCellValue()));
}
if(null != row.getCell(7)) {
if (null != row.getCell(7)) {
row.getCell(7).setCellType(Cell.CELL_TYPE_STRING);
if (StringUtils.isNotBlank(row.getCell(7).getStringCellValue())) {
bill.setPoundage(new BigDecimal(row.getCell(7).getStringCellValue()));
}
}
if(null != row.getCell(10)) {
if (null != row.getCell(10)) {
bill.setRemak(row.getCell(10).getStringCellValue());
}
return bill;
}
}
package cn.gq.financial.utils;
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.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLContextBuilder;
import org.apache.http.conn.ssl.TrustStrategy;
import org.apache.http.conn.ssl.X509HostnameVerifier;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLContextBuilder;
import org.apache.http.conn.ssl.TrustStrategy;
import org.apache.http.conn.ssl.X509HostnameVerifier;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLException;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocket;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLException;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocket;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.security.GeneralSecurityException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class HttpUtils {
private static PoolingHttpClientConnectionManager connMgr;
private static RequestConfig requestConfig;
private static final int MAX_TIMEOUT = 7000;
static {
// 设置连接池
connMgr = new PoolingHttpClientConnectionManager();
// 设置连接池大小
connMgr.setMaxTotal(5000);
connMgr.setDefaultMaxPerRoute(connMgr.getMaxTotal());
RequestConfig.Builder configBuilder = RequestConfig.custom();
// 设置连接超时
configBuilder.setConnectTimeout(MAX_TIMEOUT);
// 设置读取超时
configBuilder.setSocketTimeout(MAX_TIMEOUT);
// 设置从连接池获取连接实例的超时
configBuilder.setConnectionRequestTimeout(MAX_TIMEOUT);
// 在提交请求之前 测试连接是否可用
configBuilder.setStaleConnectionCheckEnabled(true);
requestConfig = configBuilder.build();
}
/**
* 发送 GET 请求(HTTP),不带输入数据
* @param url
* @return
*/
public static String doGet(String url) {
return doGet(url, new HashMap<String, Object>());
}
/**
* 发送 GET 请求(HTTP),K-V形式
* @param url
* @param params
* @return
*/
public static String doGet(String url, Map<String, Object> params) {
String apiUrl = url;
StringBuffer param = new StringBuffer();
int i = 0;
for (String key : params.keySet()) {
if (i == 0)
param.append("?");
else
param.append("&");
param.append(key).append("=").append(params.get(key));
i++;
}
apiUrl += param;
String result = null;
HttpClient httpclient = new DefaultHttpClient();
try {
HttpGet httpPost = new HttpGet(apiUrl);
HttpResponse response = httpclient.execute(httpPost);
int statusCode = response.getStatusLine().getStatusCode();
System.out.println("执行状态码 : " + statusCode);
HttpEntity entity = response.getEntity();
if (entity != null) {
InputStream instream = entity.getContent();
result = IOUtils.toString(instream, "UTF-8");
}
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
/**
* 发送 POST 请求(HTTP),不带输入数据
* @param apiUrl
* @return
*/
public static String doPost(String apiUrl) {
return doPost(apiUrl, new HashMap<String, Object>());
}
/**
* 发送 POST 请求(HTTP),K-V形式
* @param apiUrl API接口URL
* @param params 参数map
* @return
*/
public static String doPost(String apiUrl, Map<String, Object> params) {
CloseableHttpClient httpClient = HttpClients.createDefault();
String httpStr = null;
HttpPost httpPost = new HttpPost(apiUrl);
CloseableHttpResponse response = null;
try {
httpPost.setConfig(requestConfig);
List<NameValuePair> pairList = new ArrayList<>(params.size());
for (Map.Entry<String, Object> entry : params.entrySet()) {
NameValuePair pair = new BasicNameValuePair(entry.getKey(), entry
.getValue().toString());
pairList.add(pair);
}
httpPost.setEntity(new UrlEncodedFormEntity(pairList, Charset.forName("UTF-8")));
response = httpClient.execute(httpPost);
System.out.println(response.toString());
HttpEntity entity = response.getEntity();
httpStr = EntityUtils.toString(entity, "UTF-8");
} catch (IOException e) {
e.printStackTrace();
} finally {
if (response != null) {
try {
EntityUtils.consume(response.getEntity());
} catch (IOException e) {
e.printStackTrace();
}
}
}
return httpStr;
}
/**
* 发送 POST 请求(HTTP),JSON形式
* @param apiUrl
* @param json json对象
* @return
*/
public static String doPost(String apiUrl, Object json) {
CloseableHttpClient httpClient = HttpClients.createDefault();
String httpStr = null;
HttpPost httpPost = new HttpPost(apiUrl);
CloseableHttpResponse response = null;
try {
httpPost.setConfig(requestConfig);
StringEntity stringEntity = new StringEntity(json.toString(),"UTF-8");//解决中文乱码问题
stringEntity.setContentEncoding("UTF-8");
stringEntity.setContentType("application/json");
httpPost.setEntity(stringEntity);
response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
System.out.println(response.getStatusLine().getStatusCode());
httpStr = EntityUtils.toString(entity, "UTF-8");
} catch (IOException e) {
e.printStackTrace();
} finally {
if (response != null) {
try {
EntityUtils.consume(response.getEntity());
} catch (IOException e) {
e.printStackTrace();
}
}
}
return httpStr;
}
/**
* 发送 SSL POST 请求(HTTPS),K-V形式
* @param apiUrl API接口URL
* @param params 参数map
* @return
*/
public static String doPostSSL(String apiUrl, Map<String, Object> params) {
CloseableHttpClient httpClient = HttpClients.custom().setSSLSocketFactory(createSSLConnSocketFactory()).setConnectionManager(connMgr).setDefaultRequestConfig(requestConfig).build();
HttpPost httpPost = new HttpPost(apiUrl);
CloseableHttpResponse response = null;
String httpStr = null;
try {
httpPost.setConfig(requestConfig);
List<NameValuePair> pairList = new ArrayList<NameValuePair>(params.size());
for (Map.Entry<String, Object> entry : params.entrySet()) {
NameValuePair pair = new BasicNameValuePair(entry.getKey(), entry
.getValue().toString());
pairList.add(pair);
}
httpPost.setEntity(new UrlEncodedFormEntity(pairList, Charset.forName("utf-8")));
response = httpClient.execute(httpPost);
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode != HttpStatus.SC_OK) {
return null;
}
HttpEntity entity = response.getEntity();
if (entity == null) {
return null;
}
httpStr = EntityUtils.toString(entity, "utf-8");
} catch (Exception e) {
e.printStackTrace();
} finally {
if (response != null) {
try {
EntityUtils.consume(response.getEntity());
} catch (IOException e) {
e.printStackTrace();
}
}
}
return httpStr;
}
/**
* 发送 SSL POST 请求(HTTPS),JSON形式
* @param apiUrl API接口URL
* @param json JSON对象
* @return
*/
public static String doPostSSL(String apiUrl, Object json) {
CloseableHttpClient httpClient = HttpClients.custom().setSSLSocketFactory(createSSLConnSocketFactory()).setConnectionManager(connMgr).setDefaultRequestConfig(requestConfig).build();
HttpPost httpPost = new HttpPost(apiUrl);
CloseableHttpResponse response = null;
String httpStr = null;
try {
httpPost.setConfig(requestConfig);
StringEntity stringEntity = new StringEntity(json.toString(),"UTF-8");//解决中文乱码问题
stringEntity.setContentEncoding("UTF-8");
stringEntity.setContentType("application/json");
httpPost.setEntity(stringEntity);
response = httpClient.execute(httpPost);
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode != HttpStatus.SC_OK) {
return null;
}
HttpEntity entity = response.getEntity();
if (entity == null) {
return null;
}
httpStr = EntityUtils.toString(entity, "utf-8");
} catch (Exception e) {
e.printStackTrace();
} finally {
if (response != null) {
try {
EntityUtils.consume(response.getEntity());
} catch (IOException e) {
e.printStackTrace();
}
}
}
return httpStr;
}
/**
* 创建SSL安全连接
*
* @return
*/
private static SSLConnectionSocketFactory createSSLConnSocketFactory() {
SSLConnectionSocketFactory sslsf = null;
try {
SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
return true;
}
}).build();
sslsf = new SSLConnectionSocketFactory(sslContext, new X509HostnameVerifier() {
@Override
public boolean verify(String arg0, SSLSession arg1) {
return true;
}
@Override
public void verify(String host, SSLSocket ssl) throws IOException {
}
@Override
public void verify(String host, X509Certificate cert) throws SSLException {
}
@Override
public void verify(String host, String[] cns, String[] subjectAlts) throws SSLException {
}
});
} catch (GeneralSecurityException e) {
e.printStackTrace();
}
return sslsf;
}
/**
* 测试方法
* @param args
*/
public static void main(String[] args) throws Exception {
}
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.security.GeneralSecurityException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class HttpUtils {
private static PoolingHttpClientConnectionManager connMgr;
private static RequestConfig requestConfig;
private static final int MAX_TIMEOUT = 7000;
static {
// 设置连接池
connMgr = new PoolingHttpClientConnectionManager();
// 设置连接池大小
connMgr.setMaxTotal(5000);
connMgr.setDefaultMaxPerRoute(connMgr.getMaxTotal());
RequestConfig.Builder configBuilder = RequestConfig.custom();
// 设置连接超时
configBuilder.setConnectTimeout(MAX_TIMEOUT);
// 设置读取超时
configBuilder.setSocketTimeout(MAX_TIMEOUT);
// 设置从连接池获取连接实例的超时
configBuilder.setConnectionRequestTimeout(MAX_TIMEOUT);
// 在提交请求之前 测试连接是否可用
configBuilder.setStaleConnectionCheckEnabled(true);
requestConfig = configBuilder.build();
}
/**
* 发送 GET 请求(HTTP),不带输入数据
*
* @param url
* @return
*/
public static String doGet(String url) {
return doGet(url, new HashMap<String, Object>());
}
/**
* 发送 GET 请求(HTTP),K-V形式
*
* @param url
* @param params
* @return
*/
public static String doGet(String url, Map<String, Object> params) {
String apiUrl = url;
StringBuffer param = new StringBuffer();
int i = 0;
for (String key : params.keySet()) {
if (i == 0)
param.append("?");
else
param.append("&");
param.append(key).append("=").append(params.get(key));
i++;
}
apiUrl += param;
String result = null;
CloseableHttpClient httpclient = HttpClients.custom().build();
try {
HttpGet httpPost = new HttpGet(apiUrl);
CloseableHttpResponse response = null;
try {
response = httpclient.execute(httpPost);
int statusCode = response.getStatusLine().getStatusCode();
System.out.println("执行状态码 : " + statusCode);
HttpEntity entity = response.getEntity();
if (entity != null) {
InputStream instream = entity.getContent();
result = IOUtils.toString(instream, "UTF-8");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (response != null) {
response.close();
}
}
} catch (Exception ex) {
ex.printStackTrace();
} finally {
if (httpclient != null) {
try {
httpclient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return result;
}
/**
* 发送 POST 请求(HTTP),不带输入数据
*
* @param apiUrl
* @return
*/
public static String doPost(String apiUrl) {
return doPost(apiUrl, new HashMap<String, Object>());
}
/**
* 发送 POST 请求(HTTP),K-V形式
*
* @param apiUrl API接口URL
* @param params 参数map
* @return
*/
public static String doPost(String apiUrl, Map<String, Object> params) {
CloseableHttpClient httpClient = HttpClients.createDefault();
String httpStr = null;
HttpPost httpPost = new HttpPost(apiUrl);
CloseableHttpResponse response = null;
try {
httpPost.setConfig(requestConfig);
List<NameValuePair> pairList = new ArrayList<>(params.size());
for (Map.Entry<String, Object> entry : params.entrySet()) {
NameValuePair pair = new BasicNameValuePair(entry.getKey(), entry
.getValue().toString());
pairList.add(pair);
}
httpPost.setEntity(new UrlEncodedFormEntity(pairList, Charset.forName("UTF-8")));
response = httpClient.execute(httpPost);
System.out.println(response.toString());
HttpEntity entity = response.getEntity();
httpStr = EntityUtils.toString(entity, "UTF-8");
} catch (IOException e) {
e.printStackTrace();
} finally {
if (response != null) {
try {
EntityUtils.consume(response.getEntity());
} catch (IOException e) {
e.printStackTrace();
}
}
}
return httpStr;
}
/**
* 发送 POST 请求(HTTP),JSON形式
*
* @param apiUrl
* @param json json对象
* @return
*/
public static String doPost(String apiUrl, Object json) {
CloseableHttpClient httpClient = HttpClients.createDefault();
String httpStr = null;
HttpPost httpPost = new HttpPost(apiUrl);
CloseableHttpResponse response = null;
try {
httpPost.setConfig(requestConfig);
StringEntity stringEntity = new StringEntity(json.toString(), "UTF-8");//解决中文乱码问题
stringEntity.setContentEncoding("UTF-8");
stringEntity.setContentType("application/json");
httpPost.setEntity(stringEntity);
response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
System.out.println(response.getStatusLine().getStatusCode());
httpStr = EntityUtils.toString(entity, "UTF-8");
} catch (IOException e) {
e.printStackTrace();
} finally {
if (response != null) {
try {
EntityUtils.consume(response.getEntity());
} catch (IOException e) {
e.printStackTrace();
}
}
}
return httpStr;
}
/**
* 发送 SSL POST 请求(HTTPS),K-V形式
*
* @param apiUrl API接口URL
* @param params 参数map
* @return
*/
public static String doPostSSL(String apiUrl, Map<String, Object> params) {
CloseableHttpClient httpClient = HttpClients.custom().setSSLSocketFactory(createSSLConnSocketFactory()).setConnectionManager(connMgr).setDefaultRequestConfig(requestConfig).build();
HttpPost httpPost = new HttpPost(apiUrl);
CloseableHttpResponse response = null;
String httpStr = null;
try {
httpPost.setConfig(requestConfig);
List<NameValuePair> pairList = new ArrayList<NameValuePair>(params.size());
for (Map.Entry<String, Object> entry : params.entrySet()) {
NameValuePair pair = new BasicNameValuePair(entry.getKey(), entry
.getValue().toString());
pairList.add(pair);
}
httpPost.setEntity(new UrlEncodedFormEntity(pairList, Charset.forName("utf-8")));
response = httpClient.execute(httpPost);
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode != HttpStatus.SC_OK) {
return null;
}
HttpEntity entity = response.getEntity();
if (entity == null) {
return null;
}
httpStr = EntityUtils.toString(entity, "utf-8");
} catch (Exception e) {
e.printStackTrace();
} finally {
if (response != null) {
try {
EntityUtils.consume(response.getEntity());
} catch (IOException e) {
e.printStackTrace();
}
}
}
return httpStr;
}
/**
* 发送 SSL POST 请求(HTTPS),JSON形式
*
* @param apiUrl API接口URL
* @param json JSON对象
* @return
*/
public static String doPostSSL(String apiUrl, Object json) {
CloseableHttpClient httpClient = HttpClients.custom().setSSLSocketFactory(createSSLConnSocketFactory()).setConnectionManager(connMgr).setDefaultRequestConfig(requestConfig).build();
HttpPost httpPost = new HttpPost(apiUrl);
CloseableHttpResponse response = null;
String httpStr = null;
try {
httpPost.setConfig(requestConfig);
StringEntity stringEntity = new StringEntity(json.toString(), "UTF-8");//解决中文乱码问题
stringEntity.setContentEncoding("UTF-8");
stringEntity.setContentType("application/json");
httpPost.setEntity(stringEntity);
response = httpClient.execute(httpPost);
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode != HttpStatus.SC_OK) {
return null;
}
HttpEntity entity = response.getEntity();
if (entity == null) {
return null;
}
httpStr = EntityUtils.toString(entity, "utf-8");
} catch (Exception e) {
e.printStackTrace();
} finally {
if (response != null) {
try {
EntityUtils.consume(response.getEntity());
} catch (IOException e) {
e.printStackTrace();
}
}
}
return httpStr;
}
/**
* 创建SSL安全连接
*
* @return
*/
private static SSLConnectionSocketFactory createSSLConnSocketFactory() {
SSLConnectionSocketFactory sslsf = null;
try {
SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
return true;
}
}).build();
sslsf = new SSLConnectionSocketFactory(sslContext, new X509HostnameVerifier() {
@Override
public boolean verify(String arg0, SSLSession arg1) {
return true;
}
@Override
public void verify(String host, SSLSocket ssl) throws IOException {
}
@Override
public void verify(String host, X509Certificate cert) throws SSLException {
}
@Override
public void verify(String host, String[] cns, String[] subjectAlts) throws SSLException {
}
});
} catch (GeneralSecurityException e) {
e.printStackTrace();
}
return sslsf;
}
/**
* 测试方法
*
* @param args
*/
public static void main(String[] args) throws Exception {
}
}
\ No newline at end of file
......@@ -33,8 +33,9 @@
DiscardPolicy:抛弃当前任务、暂不支持;会导致被丢弃的任务无法再次被执行
<bean class="java.util.concurrent.ThreadPoolExecutor$CallerRunsPolicy" />
</property> -->
<property name="awaitTerminationSeconds" value="300" />
</bean>
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
......@@ -279,6 +280,9 @@
<property name="maxActive" value="50"/>
<!--minIdle: 最小空闲连接-->
<property name="minIdle" value="5"/>
<property name="testOnBorrow" value="true" />
<property name="validationQuery" value="select 1" />
<property name="maxWait" value="10000" />
</bean>
<bean id="localRepaymentSqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
......
......@@ -3,9 +3,9 @@ log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d [%t] %-5p - %c %x - %m%n
log4j.appender.R=error
log4j.logger.R=ERROR
log4j.appender.R=org.apache.log4j.DailyRollingFileAppender
log4j.appender.R.File=/logs/my-repay-handler.log
log4j.appender.R.File=/logs/info.log
log4j.appender.RollingFile.DatePattern=yyyy-MM-dd'.log'
log4j.appender.R.layout=org.apache.log4j.PatternLayout
log4j.appender.R.layout.ConversionPattern=%d [%t] %-5p - %c %x - %m%n
......@@ -17,11 +17,4 @@ log4j.logger.com.ibatis.sqlmap.engine.impl.SqlMapClientDelegate = debug
log4j.logger.java.sql.Connection = debug
log4j.logger.java.sql.Statement = debug
log4j.logger.java.sql.PreparedStatement = debug,R
log4j.logger.java.sql.ResultSet =debug
log4j.appender.R=info
log4j.appender.R=org.apache.log4j.DailyRollingFileAppender
log4j.appender.R.File=/logs/info.log
log4j.appender.RollingFile.DatePattern=yyyy-MM-dd'.log'
log4j.appender.R.layout=org.apache.log4j.PatternLayout
log4j.appender.R.layout.ConversionPattern=%d [%t] %-5p - %c %x - %m%n
\ No newline at end of file
log4j.logger.java.sql.ResultSet =debug
\ No newline at end of file
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