Commit 1018d0bd by yanlveming

同步

parent 8cf556b3
package com.library.TopUp.Http;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import javax.net.ssl.*;
/**
* 提供通过HTTP协议获取内容的方法 <br/>
* 所有提供方法中的params参数在内部不会进行自动的url encode,如果提交参数需要进行url encode,请调用方自行处理
*
* @author admin
* @Description: HTTP请求代理工具
*/
public class HttpUtils {
// private static final Logger logger = LoggerFactory.getLogger(HttpUtils.class);
/**
* 支持的Http method
*/
private static enum HttpMethod {
POST, DELETE, GET, PUT, HEAD
}
@SuppressWarnings({"unchecked", "rawtypes"})
private static String invokeUrl(String url, Map params, Map<String, String> headers, int connectTimeout, int readTimeout, String encoding, HttpMethod method) {
//构造请求参数字符串
StringBuilder paramsStr = null;
if (params != null) {
paramsStr = new StringBuilder();
Set<Map.Entry> entries = params.entrySet();
for (Map.Entry entry : entries) {
String value = (entry.getValue() != null) ? (String.valueOf(entry.getValue())) : "";
paramsStr.append(entry.getKey() + "=" + value + "&");
}
//只有POST方法才能通过OutputStream(即form的形式)提交参数
if (method != HttpMethod.POST) {
url += "?" + paramsStr.toString();
}
}
URL uUrl = null;
HttpURLConnection conn = null;
BufferedWriter out = null;
BufferedReader in = null;
try {
//创建和初始化连接
uUrl = new URL(url);
conn = (HttpURLConnection) uUrl.openConnection();
conn.setRequestProperty("content-type", "application/x-www-form-urlencoded");
conn.setRequestMethod(method.toString());
conn.setDoOutput(true);
conn.setDoInput(true);
//设置连接超时时间
conn.setConnectTimeout(connectTimeout);
//设置读取超时时间
conn.setReadTimeout(readTimeout);
//指定请求header参数
if (headers != null && headers.size() > 0) {
Set<String> headerSet = headers.keySet();
for (String key : headerSet) {
conn.setRequestProperty(key, headers.get(key));
}
}
if (paramsStr != null && method == HttpMethod.POST) {
//发送请求参数
out = new BufferedWriter(new OutputStreamWriter(conn.getOutputStream(), encoding));
out.write(paramsStr.toString());
out.flush();
}
//接收返回结果
StringBuilder result = new StringBuilder();
in = new BufferedReader(new InputStreamReader(conn.getInputStream(), encoding));
if (in != null) {
String line = "";
while ((line = in.readLine()) != null) {
result.append(line);
}
}
return result.toString();
} catch (Exception e) {
System.out.println("调用接口[" + url + "]失败!请求URL:" + url + ",参数:" + params+" 返回值:"+ e.getLocalizedMessage());
//处理错误流,提高http连接被重用的几率
try {
byte[] buf = new byte[100];
InputStream es = conn.getErrorStream();
if (es != null) {
while (es.read(buf) > 0) {
;
}
es.close();
}
} catch (Exception e1) {
e1.printStackTrace();
}
} finally {
try {
if (out != null) {
out.close();
}
} catch (Exception e) {
e.printStackTrace();
}
try {
if (in != null) {
in.close();
}
} catch (Exception e) {
e.printStackTrace();
}
//关闭连接
if (conn != null) {
conn.disconnect();
}
}
return null;
}
/**
* POST方法提交Http请求,语义为“增加” <br/>
* 注意:Http方法中只有POST方法才能使用body来提交内容
*
* @param url 资源路径(如果url中已经包含参数,则params应该为null)
* @param params 参数
* @param connectTimeout 连接超时时间(单位为ms)
* @param readTimeout 读取超时时间(单位为ms)
* @param charset 字符集(一般该为“utf-8”)
* @return
*/
public static String post(String url, Map params, int connectTimeout, int readTimeout, String charset) {
return invokeUrl(url, params, null, connectTimeout, readTimeout, charset, HttpMethod.POST);
}
/**
* POST方法提交Http请求,语义为“增加” <br/>
* 注意:Http方法中只有POST方法才能使用body来提交内容
*
* @param url 资源路径(如果url中已经包含参数,则params应该为null)
* @param params 参数
* @param headers 请求头参数
* @param connectTimeout 连接超时时间(单位为ms)
* @param readTimeout 读取超时时间(单位为ms)
* @param charset 字符集(一般该为“utf-8”)
* @return
*/
public static String post(String url, Map params, Map<String, String> headers, int connectTimeout, int readTimeout, String charset) {
return invokeUrl(url, params, headers, connectTimeout, readTimeout, charset, HttpMethod.POST);
}
/**
* GET方法提交Http请求,语义为“查询”
*
* @param url 资源路径(如果url中已经包含参数,则params应该为null)
* @param params 参数
* @param connectTimeout 连接超时时间(单位为ms)
* @param readTimeout 读取超时时间(单位为ms)
* @param charset 字符集(一般该为“utf-8”)
* @return
*/
public static String get(String url, Map params, int connectTimeout, int readTimeout, String charset) {
return invokeUrl(url, params, null, connectTimeout, readTimeout, charset, HttpMethod.GET);
}
/**
* GET方法提交Http请求,语义为“查询”
*
* @param url 资源路径(如果url中已经包含参数,则params应该为null)
* @param params 参数
* @param headers 请求头参数
* @param connectTimeout 连接超时时间(单位为ms)
* @param readTimeout 读取超时时间(单位为ms)
* @param charset 字符集(一般该为“utf-8”)
* @return
*/
public static String get(String url, Map params, Map<String, String> headers, int connectTimeout, int readTimeout, String charset) {
return invokeUrl(url, params, headers, connectTimeout, readTimeout, charset, HttpMethod.GET);
}
/**
* PUT方法提交Http请求,语义为“更改” <br/>
* 注意:PUT方法也是使用url提交参数内容而非body,所以参数最大长度收到服务器端实现的限制,Resin大概是8K
*
* @param url 资源路径(如果url中已经包含参数,则params应该为null)
* @param params 参数
* @param connectTimeout 连接超时时间(单位为ms)
* @param readTimeout 读取超时时间(单位为ms)
* @param charset 字符集(一般该为“utf-8”)
* @return
*/
public static String put(String url, Map params, int connectTimeout, int readTimeout, String charset) {
return invokeUrl(url, params, null, connectTimeout, readTimeout, charset, HttpMethod.PUT);
}
/**
* PUT方法提交Http请求,语义为“更改” <br/>
* 注意:PUT方法也是使用url提交参数内容而非body,所以参数最大长度收到服务器端实现的限制,Resin大概是8K
*
* @param url 资源路径(如果url中已经包含参数,则params应该为null)
* @param params 参数
* @param headers 请求头参数
* @param connectTimeout 连接超时时间(单位为ms)
* @param readTimeout 读取超时时间(单位为ms)
* @param charset 字符集(一般该为“utf-8”)
* @return
*/
public static String put(String url, Map params, Map<String, String> headers, int connectTimeout, int readTimeout, String charset) {
return invokeUrl(url, params, headers, connectTimeout, readTimeout, charset, HttpMethod.PUT);
}
/**
* DELETE方法提交Http请求,语义为“删除”
*
* @param url 资源路径(如果url中已经包含参数,则params应该为null)
* @param params 参数
* @param connectTimeout 连接超时时间(单位为ms)
* @param readTimeout 读取超时时间(单位为ms)
* @param charset 字符集(一般该为“utf-8”)
* @return
*/
public static String delete(String url, Map params, int connectTimeout, int readTimeout, String charset) {
return invokeUrl(url, params, null, connectTimeout, readTimeout, charset, HttpMethod.DELETE);
}
/**
* DELETE方法提交Http请求,语义为“删除”
*
* @param url 资源路径(如果url中已经包含参数,则params应该为null)
* @param params 参数
* @param headers 请求头参数
* @param connectTimeout 连接超时时间(单位为ms)
* @param readTimeout 读取超时时间(单位为ms)
* @param charset 字符集(一般该为“utf-8”)
* @return
*/
public static String delete(String url, Map params, Map<String, String> headers, int connectTimeout, int readTimeout, String charset) {
return invokeUrl(url, params, headers, connectTimeout, readTimeout, charset, HttpMethod.DELETE);
}
/**
* HEAD方法提交Http请求,语义同GET方法 <br/>
* 跟GET方法不同的是,用该方法请求,服务端不返回message body只返回头信息,能节省带宽
*
* @param url 资源路径(如果url中已经包含参数,则params应该为null)
* @param params 参数
* @param connectTimeout 连接超时时间(单位为ms)
* @param readTimeout 读取超时时间(单位为ms)
* @param charset 字符集(一般该为“utf-8”)
* @return
*/
public static String head(String url, Map params, int connectTimeout, int readTimeout, String charset) {
return invokeUrl(url, params, null, connectTimeout, readTimeout, charset, HttpMethod.HEAD);
}
/**
* HEAD方法提交Http请求,语义同GET方法 <br/>
* 跟GET方法不同的是,用该方法请求,服务端不返回message body只返回头信息,能节省带宽
*
* @param url 资源路径(如果url中已经包含参数,则params应该为null)
* @param params 参数
* @param headers 请求头参数
* @param connectTimeout 连接超时时间(单位为ms)
* @param readTimeout 读取超时时间(单位为ms)
* @param charset 字符集(一般该为“utf-8”)
* @return
*/
public static String head(String url, Map params, Map<String, String> headers, int connectTimeout, int readTimeout, String charset) {
return invokeUrl(url, params, headers, connectTimeout, readTimeout, charset, HttpMethod.HEAD);
}
public static void main(String[] args) {
// Map params = new HashMap();
// params.put("phoneNo", "中文");
// String str = HttpUtils.get("http://localhost:8080/TopUpCambodian_war_exploded/Common/FindQNYToken",
// params,
// 3000,
// 3000,
// "UTF-8");
// System.out.println(str);
Map params = new HashMap();
// params.put("serviceType", "PINCODE");
// params.put("networkOperator", "METFONE");
// params.put("pinCodeId", "2");
// params.put("refId", "123123111");
params.put("serviceType", "TOPUP");
params.put("transAmount", "1");
params.put("currency", "USD");
params.put("refId", "1121");
params.put("customerPhoneNumber", "855883970777");
// params.put("serviceType", "TELCO_BILL_PAYMENT");
// params.put("networkOperator", "METFONE");
// params.put("transAmount", "450.00");
// params.put("currency", "USD");
// params.put("extraId", "680");
// params.put("refId", "11");
// params.put("paymentCode", "883970777");
Map<String,String> heardMap=new HashMap<>();
heardMap.put("Authorization","epa 2478e27af578e11a6af86a8320562124240f5c972e8039cd9c564e53d643bb31");
heardMap.put("e-language","English");
heardMap.put("Content-Type","application/json");
heardMap.put("Accept","application/json");
String url="https://payment.emoney.com.kh:8888/ePayTest/telco/init";
String urlTest="https://36.37.242.116:8301/ePayTest/telco/init";
String str=HttpUtils.post(url,
params,heardMap
,3000,3000,"UTF-8");
System.out.println(str);
}
}
package com.library.TopUp.Http;
import com.google.gson.Gson;
import org.apache.commons.lang3.StringUtils;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLSession;
import javax.servlet.http.HttpServletResponse;
/**
* https post发送工具 绕过ssl
*
* @author 超神之巅
*
*/
public class HttpsTool {
private static final String LINE_SEPARATOR = System.getProperty("line.separator");
static HostnameVerifier hv = new HostnameVerifier() {
public boolean verify(String urlHostName, SSLSession session) {
System.out.println("Warning: URL Host: " + urlHostName + " vs. "
+ session.getPeerHost());
return true;
}
};
private static void trustAllHttpsCertificates() throws Exception {
javax.net.ssl.TrustManager[] trustAllCerts = new javax.net.ssl.TrustManager[1];
javax.net.ssl.TrustManager tm = new miTM();
trustAllCerts[0] = tm;
javax.net.ssl.SSLContext sc = javax.net.ssl.SSLContext
.getInstance("SSL");
sc.init(null, trustAllCerts, null);
javax.net.ssl.HttpsURLConnection.setDefaultSSLSocketFactory(sc
.getSocketFactory());
}
static class miTM implements javax.net.ssl.TrustManager,
javax.net.ssl.X509TrustManager {
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return null;
}
public boolean isServerTrusted(
java.security.cert.X509Certificate[] certs) {
return true;
}
public boolean isClientTrusted(
java.security.cert.X509Certificate[] certs) {
return true;
}
public void checkServerTrusted(
java.security.cert.X509Certificate[] certs, String authType)
throws java.security.cert.CertificateException {
return;
}
public void checkClientTrusted(
java.security.cert.X509Certificate[] certs, String authType)
throws java.security.cert.CertificateException {
return;
}
}
/**
* 发送报文
*
* 通信失败时返回分两种:一种是抛异常,一种是返回"",本方法取前者
*
* @param requestData
* 请求报文
* @param headMap
* head请求头参数 conn.setRequestProperty(key,value)
* @param urlStr
* 请求地址
* @param sendEncoding
* 请求编码
* @param recvEncoding
* 返回编码
* @param connectionTimeout
* 链接超时时间 1000代表 1秒
* @param readTimeout
* 读取超时时间 1000代表1秒
* @return
* @throws IOException
* @author 超神之巅
*/
public static String send(String requestData,Map<String,String> headMap, String urlStr, String sendEncoding, String recvEncoding,
int connectionTimeout, int readTimeout,String contentType) throws Exception {
URL url = null;
HttpsURLConnection conn = null;
ByteArrayOutputStream byteOut = null;
BufferedReader readInfo = null;
StringBuilder retBuilder = new StringBuilder();// 这里用不着多线程安全的StringBuffer
OutputStream out = null;
String line = null;
StringBuilder reqDetailProcedure = new StringBuilder();// 这里用不着多线程安全的StringBuffer
Date startTime = new Date();
reqDetailProcedure.append("请求时间:【" + DATE_FORMATER.format(startTime) + "】").append("\r\n");
reqDetailProcedure.append("请求地址:【" + urlStr + "】").append("\r\n");
reqDetailProcedure.append("真实请求方式及编码:【post " + sendEncoding + "】").append("\r\n");
reqDetailProcedure.append("期望返回编码:【" + recvEncoding + "】").append("\r\n");
reqDetailProcedure.append("请求超时时间:【" + readTimeout / 1000 + "s】").append("\r\n");
reqDetailProcedure.append("请求报文:【" + requestData + "】").append("\r\n");
try {
// 如有必要,给?后的参数加encode(xxx,"UTF-8"),不然目标系统可能收到的request.getParameter()是乱码
// String arg = java.net.URLEncoder.encode("中国","UTF-8");
// url = new URL(urlStr+"?deptname="+arg);
url = new URL(urlStr);
trustAllHttpsCertificates();
HttpsURLConnection.setDefaultHostnameVerifier(hv);
conn = (HttpsURLConnection) url.openConnection();
conn.setRequestMethod("POST");
// 新增部分
//conn.setHostnameVerifier(new TrustAnyHostnameVerifier());
conn.setRequestProperty("SOAPAction", "\"\"");
conn.setRequestProperty("Accept", "application/xml, application/json,application/dime, multipart/related, text/*");
// 如果没有下面这一行代码,服务器端可以通过request.getParameter()和request.getInputStream()都接收到相同信息
// Content-Type相关知识链接: http://www.cnblogs.com/whatlonelytear/p/6187575.html
// conn如果不设Content-Type,则默认成application/x-www-form-urlencoded
// 当然也可以配置成application/x-www-form-urlencoded;charset=UTF-8,此时要求服务端返回UTF-8编码,如果本地还用gbk去解码,有可能得到乱码
conn.setRequestProperty("Content-Type", contentType);
// 如果把Content-Type的类型改变成非application/x-www-form-urlencoded,如改成text/xml,
// 则目标服务器端仅能通过request.getInputStream()接收信息, 如conn.setRequestProperty("Content-Type", "text/xml;charset=GBK");
// Content-Type各类型解释: http://blog.csdn.net/blueheart20/article/details/45174399
// conn.setRequestProperty("Accept-Charset", "utf-8");//未知
//Cache-Control说明链接:http://huangyunbin.iteye.com/blog/1943310 或 http://www.cnblogs.com/whatlonelytear/articles/6385390.html
conn.setRequestProperty("Cache-Control", "no-cache");
//设置head头,如果已存在,则覆盖之前的head配置
if(headMap != null){
for(Map.Entry<String, String > entry : headMap.entrySet()){
conn.setRequestProperty(entry.getKey(),entry.getValue());
}
}
// conn.setRequestProperty("appName", appName);//各系统需要设置应用系统名,如电销为telesales(无意义,本人自定义)
conn.setUseCaches(false); // 忽略缓存
// get请求用不到conn.getOutputStream(),因为参数直接追加在地址后面,因此默认是false.
// post请求(比如:文件上传)需要往服务区传输大量的数据,这些数据是放在http的body里面的,因此需要在建立连接以后,往服务端写数据.
// 因为总是使用conn.getInputStream()获取服务端的响应,因此默认值是true.
conn.setDoOutput(true); // 使用 URL
// 连接进行输出,允许使用conn.getOutputStream().write()
conn.setDoInput(true); // 使用 URL
// 连接进行输入,允许使用conn.getInputStream().read();
conn.setConnectTimeout(connectionTimeout);// 链接超时
conn.setReadTimeout(readTimeout);// 读取超时
conn.connect();// 建立链接
byteOut = new ByteArrayOutputStream();
byteOut.write(requestData.getBytes(sendEncoding));// 以指定编码发送,如果有乱码,修改之
byte[] buf = byteOut.toByteArray();
out = conn.getOutputStream();
out.write(buf);
out.flush();
reqDetailProcedure.append("响应码和状态:【" + conn.getResponseCode() + "/" + conn.getResponseMessage() + "】").append("\r\n");
if (HttpURLConnection.HTTP_OK == conn.getResponseCode()) {// 正确返回
InputStream tempStream = conn.getInputStream();
readInfo = new BufferedReader(new java.io.InputStreamReader(tempStream, recvEncoding));// 以指定编码读取返回信息,如果有乱码,修改之
while ((line = readInfo.readLine()) != null) {
retBuilder.append(line).append(LINE_SEPARATOR);
}
} else {// 没有正确返回
// 这个else分支有冗余代码,一来代码不多,二来这个分支是经过长时间思考,还是保留了下来,方便我以后对错误做不抛异常处理等
InputStream tempStream = conn.getInputStream();// 如果响应码不是200,一般在这里就开始报异常,不会走到下面几行中去的.
readInfo = new BufferedReader(new java.io.InputStreamReader(tempStream, recvEncoding));// cannotReach
while ((line = readInfo.readLine()) != null) {// cannotReach
retBuilder.append(line);// cannotReach
}// cannotReach
reqDetailProcedure.append("@@返回异常报文:【" + retBuilder + "】").append("\r\n");// cannotReach
}
} catch (IOException e) {
e.printStackTrace();
throw e;
} finally {
// 目标服务端用response.setContentType("text/html;charset=UTF-8");然后源调用方可以用conn.getContentType()获取到[猜测,暂未测试]
// conn.getContentType()包含在Head返回的内容中.
// 返回如果带编码,可以做成动态编码去把流转成字符串,暂不优化.这是极好的l优化点.
reqDetailProcedure.append("返回内容类型及编码:【" + conn.getContentType() + "】").append("\r\n");
reqDetailProcedure.append("返回HEAD头信息:【" + conn.getHeaderFields() + "】").append("\r\n");
reqDetailProcedure.append("返回报文:【" + retBuilder.toString() + "】").append("\r\n");
Date endTime = new Date();
reqDetailProcedure.append("返回时间:【" + DATE_FORMATER.format(endTime) + "】").append("\r\n");
long diffMilliSecond = endTime.getTime() - startTime.getTime();
long diffSecond = (diffMilliSecond / 1000);
reqDetailProcedure.append("耗时:【" + diffMilliSecond + "】毫秒,大约" + "【" + diffSecond + "】秒").append("\r\n");
System.out.println(reqDetailProcedure.toString());
//ThreadLocalListContainer.put(reqDetailProcedure.toString());
// ThreadLocalMapContainer.put(KingConstants.REQ_DETAIL_PROCEDURE,reqDetailProcedure.toString())
try {
if (readInfo != null) {
readInfo.close();
}
if (byteOut != null) {
byteOut.close();
}
if (out != null) {
out.close();
}
if (conn != null) {
conn.disconnect();
}
} catch (Exception e) {
System.out.println("关闭链接出错!" + e.getMessage());
}
}
return retBuilder.toString();
}
/**
* 发送报文
*
* 通信失败时返回分两种:一种是抛异常,一种是返回"",本方法取前者
*
* @param requestData
* 请求报文
* @param urlStr
* 请求地址
* @param sendEncoding
* 请求编码
* @param recvEncoding
* 返回编码
* @param connectionTimeout
* 链接超时时间 1000代表 1秒
* @param readTimeout
* 读取超时时间 1000代表1秒
* @return
* @throws IOException
* @author 超神之巅
*/
public static String send(String requestData, String urlStr, String sendEncoding, String recvEncoding, int connectionTimeout, int readTimeout) throws Exception {
boolean flag = isJson(requestData);//是否JSON
String contentType="application/soap+xml";
if(flag) {
contentType = "application/json";
}
return send( requestData,null, urlStr, sendEncoding, recvEncoding, connectionTimeout, readTimeout,contentType);
}
/**
*
* @param filePath
* 文件绝对路径
* @param encoding
* 读取文件的编码
* @return
* @author 超神之巅
* @throws Exception
*/
public static String readStringFromFile(String filePath, String encoding) {
File file = new File(filePath);
// System.out.println("文件 "+filePath+"存在与否?: "+ file.exists());
String tempLine = null;
String retStr = "";
InputStreamReader isr = null;// way1:
// FileReader fr = null;//way2
StringBuilder sb = new StringBuilder();
try {
if (file.exists()) {
isr = new InputStreamReader(new FileInputStream(file), encoding);// way1:
// fr = new FileReader(file);//way2
BufferedReader br = new BufferedReader(isr);// way1:
// BufferedReader br = new BufferedReader(fr);;//way2:
tempLine = br.readLine();
while (tempLine != null) {
sb.append(tempLine).append(System.getProperty("line.separator"));
tempLine = br.readLine();
}
retStr = sb.toString();
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (isr != null)
isr.close();
} catch (Exception e) {
e.printStackTrace();
}
}
// System.out.println("读到的文件内容如下:");
// System.out.println(retStr);
return retStr;
}
/**
* 判断字符串是否为JSON格式
* @param str
* @return
*/
public static boolean isJson(String str){
if (StringUtils.isBlank(str)) {
return false;
}
boolean flag1 = (str.startsWith("{") && str.endsWith("}"));
boolean flag2 = (str.startsWith("[") && str.endsWith("]"));
return (flag1 || flag2);
}
/*public static final void writeInfo(HttpServletResponse resp, String errorCode, String respInfo, Map<String, Object> map) {
map.put("errorCode", errorCode);
map.put("respInfo", respInfo);
String detail = ThreadLocalListContainer.getAll();
map.put(KingConstants.DETAIL_PROCEDURE, detail);
ThreadLocalListContainer.clearAll();
// map.put(KingConstants.DETAIL_PROCEDURE, detail);
try {
// String gsonInfo = new Gson().toJson(map);//old
Gson gson = new GsonBuilder().setPrettyPrinting().create();//new
String gsonInfo = gson.toJson(map);
PrintWriter pw = resp.getWriter();
pw.print(gsonInfo);
pw.flush();
pw.close();
} catch (IOException e) {
e.printStackTrace();
}
}*/
/**
*
* @param resp
* @param errorCode
* @param respInfo
* @param map
* ......
* @time 2017年4月23日 上午9:12:43
* @author 超神之巅
*/
/*public static final void writeInfo(HttpServletResponse resp, KingResp result) {
String detail = ThreadLocalListContainer.getAll();
result.setDetailProcedure(detail);
ThreadLocalListContainer.clearAll();
try {
// String gsonInfo = new Gson().toJson(map);//old
Gson gson = new GsonBuilder().setPrettyPrinting().create();//new
String gsonInfo = gson.toJson(result);
FileTool.writeStringToFile("d:/temp/myinfo.txt", gsonInfo, "gbk", false);
PrintWriter pw = resp.getWriter();
pw.print(gsonInfo);
pw.flush();
pw.close();
} catch (IOException e) {
e.printStackTrace();
}
}*/
public static final void writeInfo(HttpServletResponse resp, String respInfo) {
try {
PrintWriter pw = resp.getWriter();
pw.print(respInfo);
pw.flush();
pw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public static final SimpleDateFormat DATE_FORMATER = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:sss");
public static void main(String[] args) throws Exception {
Map<String,String> heardMap=new HashMap<>();
heardMap.put("Authorization","epa 2478e27af578e11a6af86a8320562124240f5c972e8039cd9c564e53d643bb31");
heardMap.put("e-language","English");
heardMap.put("Content-Type","application/json");
heardMap.put("Accept","application/json");
//
//
String requestUrl = "https://36.37.242.116:8301/telco/metfone-bill/info";
Map params=new HashMap();
// params.put("serviceType", "TOPUP");
// params.put("transAmount", "1");
// params.put("currency", "USD");
// params.put("refId", "1121111");
// params.put("customerPhoneNumber", "855883970777");
params.put("paymentCode", "0979530750");
String sencXml = HttpsTool.send(new Gson().toJson(params),heardMap, requestUrl, "utf-8",
"utf-8", 300 * 1000, 300 * 1000,"application/json");// 大家最终只要使用这一句代码就可调用
System.out.println(sencXml);
// String retStr="bh1bBzuyQofPoxj8VfZrxWeD2lkULIXI4qvpBndZciAdS/mdT4EAln1AtvNoR5p73B/mxM3CzZCQHwpiEIPW+yM5xxweoI96cvwgnOUn9uixOhf99f/9pB4gbpHQmyqlwCV3qvjLMyeBWXGouJBtYWcFdKKl1PB+FDgynTRfFvcBph0tyWr0y4Rgm64OBaKQlD8O5gId1HyqQPLHofgKevU6R7+P8ZcB9pIXzWF7nPgRRC0n0aqUk+RpmKn798kjxeIv/UYH/uPrBw/Ux5ZVPOsL7RlJpDJ5rGlwHhQKWK+SnjITrp87D1nYDBsGP6hyuBwEu9OUe7ldutvKQCG3/A==";
//
// Map params=new HashMap();
//
// params.put("txPaymentTokenId", retStr);
// String conURL="https://36.37.242.116:8301/ePayTest/telco/confirm";
// String sencXml = HttpsTool.send(new Gson().toJson(params), heardMap, conURL, "utf-8",
// "utf-8", 300 * 1000, 300 * 1000, "application/json");// 大家最终只要使用这一句代码就可调用
//
// System.out.println(sencXml);
}
}
\ No newline at end of file
package com.library.TopUp.cellcard;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.library.TopUp.Http.HttpUtils;
import com.library.TopUp.Http.HttpsTool;
import com.library.TopUp.model.ResultsModel;
import org.apache.http.util.TextUtils;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Base64;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
public class CellcardSentUtils {
private final static String distributor_id = "35";
private static String access_token = "";
private static String token_type = "";
public static String getToken() {
try {
Map<String, String> params = new HashMap();
params.put("grant_type", "client_credentials");
String keyAndSecret = "v2VSgq7Q2Yqhp36s5TOzD13J5FMa:Go0wTNZdR53xNbxHwhneLF1p40Ma";
String code = Base64.getEncoder().encodeToString(keyAndSecret.getBytes("UTF-8"));
Map<String, String> heardMap = new HashMap<>();
heardMap.put("Authorization", "Basic " + code);
// heardMap.put("Content-Type", "application/json");
// heardMap.put("Accept", "application/json");
String url = "https://stg-api.cellcard.com.kh:8243/token";
// HttpClientResult clientResult = HttpClientUtils.doPost(url, heardMap, params);
//// System.out.println(new Gson().toJson(clientResult));
//// return clientResult.getContent();
String json = HttpUtils.post(url, params, heardMap, 30000, 30000, "utf-8");
return json;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public static String checkBalance(String transaction_id) {
try {
Map<String, String> params = new HashMap();
params.put("transaction_id", transaction_id);
params.put("distributor_id", distributor_id);
Map<String, String> heardMap = new HashMap<>();
heardMap.put("Authorization", token_type + " " + access_token);
heardMap.put("Content-Type", "application/x-www-form-urlencoded");
// heardMap.put("Accept", "application/json");
String url = "https://stg-api.cellcard.com.kh:8243/tom/v2/query_balance";
String json = HttpUtils.post(url, params, heardMap, 30000, 30000, "utf-8");
return json;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public static String rechargePhone(String phone, int amount, String transaction_id) {
try {
String amountStr = String.valueOf(amount * 10000);
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
String timestamp = sdf.format(new Date());
Map<String, String> params = new HashMap();
params.put("distributor_id", distributor_id);
params.put("subscriber", phone);
params.put("amount", amountStr);//Top-up amount in centi-cent 1$=10000. The minimum value is 2500.
params.put("transaction_id", transaction_id);
params.put("timestamp", timestamp);
Map<String, String> heardMap = new HashMap<>();
heardMap.put("Authorization", token_type + " " + access_token);
heardMap.put("Content-Type", "application/x-www-form-urlencoded");
String url = "https://stg-api.cellcard.com.kh:8243/tom/v2/balance_transfer";
String json = HttpUtils.post(url, params, heardMap, 30000, 30000, "utf-8");
return json;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
* By some reasons client not get response from API after top up request. It could be
* connection broken, timing out, service hanging, internal error, … To clarify the transaction
* status we implement one more step to check in OCS’s CDR which date available in 3 months
* backward.
* <p>
* SLA: This API effective after 10 minutes from client got timeout
* response (Need times to collect CDR)
*
* @param phone
* @param transaction_id
* @return
*/
public static String topUpStatus(String phone, String transaction_id) {
try {
String tokenStr = "";
String jsonToken = getToken();
if (!TextUtils.isEmpty(jsonToken)) {
JsonParser jsonParser = new JsonParser();
JsonObject jsonObject = jsonParser.parse(jsonToken).getAsJsonObject();
tokenStr = jsonObject.get("access_token") == null ? "" : jsonObject.get("access_token").getAsString();
if (!TextUtils.isEmpty(tokenStr)) {
token_type = jsonObject.get("token_type") == null ? "" : jsonObject.get("token_type").getAsString();
access_token = tokenStr;
}
}
if (TextUtils.isEmpty(tokenStr)) {
return "";
}
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
String timestamp = sdf.format(new Date());
Map<String, String> params = new HashMap();
params.put("distributor_id", distributor_id);
params.put("subscriber", phone);
params.put("transaction_id", transaction_id);
params.put("transaction_date", timestamp);
Map<String, String> heardMap = new HashMap<>();
heardMap.put("Authorization", token_type + " " + access_token);
heardMap.put("Content-Type", "application/x-www-form-urlencoded");
String url = "https://stg-api.cellcard.com.kh:8243/tom/v2/transaction_status";
String json = HttpUtils.post(url, params, heardMap, 30000, 30000, "utf-8");
return json;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public static void main(String[] args) {
// String json = topUpStatus("85561254730", "123");
ResultsModel model = sentTopUp("855061254730", "123", 1);
System.out.println("充值结果 " + model.getTip());
System.out.println("充值状态" + model.isSuccessful());
}
/**
* 发起充值
*
* @param phone 11为数的手机号码
* @param orderNum 唯一编号
* @param amount 充值金额 ,单位1美元 里面做了乘以10000的操作了
*/
public static ResultsModel sentTopUp(String phone, String orderNum, int amount) {
String tip = "";
boolean isSuccessful = false;
try {
String jsonToken = getToken();
String rechargeJson = "";
if (!TextUtils.isEmpty(jsonToken)) {
JsonParser jsonParserToken = new JsonParser();
JsonObject jsonObjectToken = jsonParserToken.parse(jsonToken).getAsJsonObject();
String tokenStr = jsonObjectToken.get("access_token") == null ? "" : jsonObjectToken.get("access_token").getAsString();
if (!TextUtils.isEmpty(tokenStr)) {
token_type = jsonObjectToken.get("token_type") == null ? "" : jsonObjectToken.get("token_type").getAsString();
access_token = tokenStr;
tip += "令牌解析成功;准备发起充值;";
/**
* 发起充值
*/
rechargeJson = rechargePhone(phone, amount, orderNum);
} else {
tip += "令牌解析失败:" + jsonToken;
}
} else {
tip += "令牌获取失败; ";
}
String transaction_id = "";
if (!TextUtils.isEmpty(rechargeJson)) {
JsonParser jsonParserRecharge = new JsonParser();
JsonObject jsonObjectRecharge = jsonParserRecharge.parse(rechargeJson).getAsJsonObject();
if (jsonObjectRecharge != null) {
JsonObject data = jsonObjectRecharge.get("data") == null ? null : jsonObjectRecharge.get("data").getAsJsonObject();
if (data != null) {
//有data对象
String error_code = data.get("error_code") == null ? "" : data.get("error_code").getAsString();
if (!TextUtils.isEmpty(error_code) && error_code.equals("0")) {
//充值成功
transaction_id = data.get("transaction_id") == null ? "" : data.get("transaction_id").getAsString();
tip += " 充值成功!!!";
isSuccessful = true;
} else {
//充值报错
tip += "充值失败,返回结果:" + rechargeJson;
}
} else {
tip += "充值无data返回,返回结果:" + rechargeJson;
}
} else {
tip += "充值报错,解析失败,返回结果:" + rechargeJson;
}
}
ResultsModel model = new ResultsModel(isSuccessful, tip);
return model;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
}
package com.library.TopUp.cellcard;
import java.io.Serializable;
/**
* Description: 封装httpClient响应结果
*
* @author JourWon
* @date Created on 2018年4月19日
*/
public class HttpClientResult implements Serializable {
public HttpClientResult(){
}
public HttpClientResult(int code) {
this.code = code;
this.content = "";
}
public HttpClientResult(int code, String content) {
this.code = code;
this.content = content;
}
/**
* 响应状态码
*/
private int code;
/**
* 响应数据
*/
private String content;
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
}
package com.library.TopUp.cellcard;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.*;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.*;
/**
* Description: httpClient工具类
*
* @author JourWon
* @date Created on 2018年4月19日
*/
public class HttpClientUtils {
// 编码格式。发送编码格式统一用UTF-8
private static final String ENCODING = "UTF-8";
// 设置连接超时时间,单位毫秒。
private static final int CONNECT_TIMEOUT = 6000;
// 请求获取数据的超时时间(即响应时间),单位毫秒。
private static final int SOCKET_TIMEOUT = 6000;
/**
* 发送get请求;不带请求头和请求参数
*
* @param url 请求地址
* @return
* @throws Exception
*/
public static HttpClientResult doGet(String url) throws Exception {
return doGet(url, null, null);
}
/**
* 发送get请求;带请求参数
*
* @param url 请求地址
* @param params 请求参数集合
* @return
* @throws Exception
*/
public static HttpClientResult doGet(String url, Map<String, String> params) throws Exception {
return doGet(url, null, params);
}
/**
* 发送get请求;带请求头和请求参数
*
* @param url 请求地址
* @param headers 请求头集合
* @param params 请求参数集合
* @return
* @throws Exception
*/
public static HttpClientResult doGet(String url, Map<String, String> headers, Map<String, String> params) throws Exception {
// 创建httpClient对象
CloseableHttpClient httpClient = HttpClients.createDefault();
// 创建访问的地址
URIBuilder uriBuilder = new URIBuilder(url);
if (params != null) {
Set<Map.Entry<String, String>> entrySet = params.entrySet();
for (Map.Entry<String, String> entry : entrySet) {
uriBuilder.setParameter(entry.getKey(), entry.getValue());
}
}
// 创建http对象
HttpGet httpGet = new HttpGet(uriBuilder.build());
/**
* setConnectTimeout:设置连接超时时间,单位毫秒。
* setConnectionRequestTimeout:设置从connect Manager(连接池)获取Connection
* 超时时间,单位毫秒。这个属性是新加的属性,因为目前版本是可以共享连接池的。
* setSocketTimeout:请求获取数据的超时时间(即响应时间),单位毫秒。 如果访问一个接口,多少时间内无法返回数据,就直接放弃此次调用。
*/
RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(CONNECT_TIMEOUT).setSocketTimeout(SOCKET_TIMEOUT).build();
httpGet.setConfig(requestConfig);
// 设置请求头
packageHeader(headers, httpGet);
// 创建httpResponse对象
CloseableHttpResponse httpResponse = null;
try {
// 执行请求并获得响应结果
return getHttpClientResult(httpResponse, httpClient, httpGet);
} finally {
// 释放资源
release(httpResponse, httpClient);
}
}
/**
* 发送post请求;不带请求头和请求参数
*
* @param url 请求地址
* @return
* @throws Exception
*/
public static HttpClientResult doPost(String url) throws Exception {
return doPost(url, null, null);
}
/**
* 发送post请求;带请求参数
*
* @param url 请求地址
* @param params 参数集合
* @return
* @throws Exception
*/
public static HttpClientResult doPost(String url, Map<String, String> params) throws Exception {
return doPost(url, null, params);
}
/**
* 发送post请求;带请求头和请求参数
*
* @param url 请求地址
* @param headers 请求头集合
* @param params 请求参数集合
* @return
* @throws Exception
*/
public static HttpClientResult doPost(String url, Map<String, String> headers, Map<String, String> params) throws Exception {
// 创建httpClient对象
CloseableHttpClient httpClient = HttpClients.createDefault();
// 创建http对象
HttpPost httpPost = new HttpPost(url);
/**
* setConnectTimeout:设置连接超时时间,单位毫秒。
* setConnectionRequestTimeout:设置从connect Manager(连接池)获取Connection
* 超时时间,单位毫秒。这个属性是新加的属性,因为目前版本是可以共享连接池的。
* setSocketTimeout:请求获取数据的超时时间(即响应时间),单位毫秒。 如果访问一个接口,多少时间内无法返回数据,就直接放弃此次调用。
*/
RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(CONNECT_TIMEOUT).setSocketTimeout(SOCKET_TIMEOUT).build();
httpPost.setConfig(requestConfig);
// 设置请求头
/*httpPost.setHeader("Cookie", "");
httpPost.setHeader("Connection", "keep-alive");
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Accept-Language", "zh-CN,zh;q=0.9");
httpPost.setHeader("Accept-Encoding", "gzip, deflate, br");
httpPost.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36");*/
packageHeader(headers, httpPost);
// 封装请求参数
packageParam(params, httpPost);
// 创建httpResponse对象
CloseableHttpResponse httpResponse = null;
try {
// 执行请求并获得响应结果
return getHttpClientResult(httpResponse, httpClient, httpPost);
} finally {
// 释放资源
release(httpResponse, httpClient);
}
}
/**
* 发送put请求;不带请求参数
*
* @param url 请求地址
* @return
* @throws Exception
*/
public static HttpClientResult doPut(String url) throws Exception {
return doPut(url);
}
/**
* 发送put请求;带请求参数
*
* @param url 请求地址
* @param params 参数集合
* @return
* @throws Exception
*/
public static HttpClientResult doPut(String url, Map<String, String> params) throws Exception {
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpPut httpPut = new HttpPut(url);
RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(CONNECT_TIMEOUT).setSocketTimeout(SOCKET_TIMEOUT).build();
httpPut.setConfig(requestConfig);
packageParam(params, httpPut);
CloseableHttpResponse httpResponse = null;
try {
return getHttpClientResult(httpResponse, httpClient, httpPut);
} finally {
release(httpResponse, httpClient);
}
}
/**
* 发送delete请求;不带请求参数
*
* @param url 请求地址
* @return
* @throws Exception
*/
public static HttpClientResult doDelete(String url) throws Exception {
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpDelete httpDelete = new HttpDelete(url);
RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(CONNECT_TIMEOUT).setSocketTimeout(SOCKET_TIMEOUT).build();
httpDelete.setConfig(requestConfig);
CloseableHttpResponse httpResponse = null;
try {
return getHttpClientResult(httpResponse, httpClient, httpDelete);
} finally {
release(httpResponse, httpClient);
}
}
/**
* 发送delete请求;带请求参数
*
* @param url 请求地址
* @param params 参数集合
* @return
* @throws Exception
*/
public static HttpClientResult doDelete(String url, Map<String, String> params) throws Exception {
if (params == null) {
params = new HashMap<String, String>();
}
params.put("_method", "delete");
return doPost(url, params);
}
/**
* Description: 封装请求头
*
* @param params
* @param httpMethod
*/
public static void packageHeader(Map<String, String> params, HttpRequestBase httpMethod) {
// 封装请求头
if (params != null) {
Set<Map.Entry<String, String>> entrySet = params.entrySet();
for (Map.Entry<String, String> entry : entrySet) {
// 设置到请求头到HttpRequestBase对象中
httpMethod.setHeader(entry.getKey(), entry.getValue());
}
}
}
/**
* Description: 封装请求参数
*
* @param params
* @param httpMethod
* @throws UnsupportedEncodingException
*/
public static void packageParam(Map<String, String> params, HttpEntityEnclosingRequestBase httpMethod)
throws UnsupportedEncodingException {
// 封装请求参数
if (params != null) {
List<NameValuePair> nvps = new ArrayList<NameValuePair>();
Set<Map.Entry<String, String>> entrySet = params.entrySet();
for (Map.Entry<String, String> entry : entrySet) {
nvps.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
System.out.println(""+entry.getKey()+" : "+ entry.getValue());
}
// 设置到请求的http对象中
httpMethod.setEntity(new UrlEncodedFormEntity(nvps, ENCODING));
}
}
/**
* Description: 获得响应结果
*
* @param httpResponse
* @param httpClient
* @param httpMethod
* @return
* @throws Exception
*/
public static HttpClientResult getHttpClientResult(CloseableHttpResponse httpResponse,
CloseableHttpClient httpClient, HttpRequestBase httpMethod) throws Exception {
// 执行请求
httpResponse = httpClient.execute(httpMethod);
// 获取返回结果
if (httpResponse != null && httpResponse.getStatusLine() != null) {
String content = "";
if (httpResponse.getEntity() != null) {
content = EntityUtils.toString(httpResponse.getEntity(), ENCODING);
}
return new HttpClientResult(httpResponse.getStatusLine().getStatusCode(), content);
}
return new HttpClientResult(HttpStatus.SC_INTERNAL_SERVER_ERROR);
}
/**
* Description: 释放资源
*
* @param httpResponse
* @param httpClient
* @throws IOException
*/
public static void release(CloseableHttpResponse httpResponse, CloseableHttpClient httpClient) throws IOException {
// 释放资源
if (httpResponse != null) {
httpResponse.close();
}
if (httpClient != null) {
httpClient.close();
}
}
}
package com.library.TopUp.mefont;
import org.apache.commons.codec.binary.Base64;
import javax.crypto.Cipher;
import java.io.FileInputStream;
import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
public class MetfoneRSAUtils {
final static String pripath = "./src/com/library/TopUp/mefont/keys/ePayTest.pri";
final static String pubpath = "./src/com/library/TopUp/mefont/keys/ePayTest.pub";
public static String encryptRSA(String plainData) {
try {
FileInputStream fis = new FileInputStream(pubpath);
byte[] byteKeyFromFile = new byte[fis.available()];
fis.read(byteKeyFromFile);
fis.close();
X509EncodedKeySpec keySpec = new
X509EncodedKeySpec(byteKeyFromFile);
KeyFactory factory = KeyFactory.getInstance("RSA");
PublicKey pubKey = factory.generatePublic(keySpec);
// Mã hoá dữ liệu
Cipher c = Cipher.getInstance("RSA/ECB/PKCS1Padding");
c.init(Cipher.ENCRYPT_MODE, pubKey);
byte encryptedByte[] = c.doFinal(plainData.getBytes());
String encrypted = Base64.encodeBase64String(encryptedByte);
return encrypted;
} catch (Exception ex) {
System.out.println(ex.getLocalizedMessage());
}
return null;
}
public static String decryptRSA(String encryptedData) {
try {
FileInputStream fis = new FileInputStream(pripath);
byte[] byteKeyFromFile = new byte[fis.available()];
fis.read(byteKeyFromFile);
fis.close();
PKCS8EncodedKeySpec keySpec = new
PKCS8EncodedKeySpec(byteKeyFromFile);
KeyFactory factory = KeyFactory.getInstance("RSA");
PrivateKey priKey = factory.generatePrivate(keySpec);
// Giải mã dữ liệu
Cipher c2 = Cipher.getInstance("RSA/ECB/PKCS1Padding");
c2.init(Cipher.DECRYPT_MODE, priKey);
String decrypted = new
String(c2.doFinal(Base64.decodeBase64(encryptedData)));
return decrypted;
} catch (Exception ex) {
System.out.println(ex.getLocalizedMessage());
}
return null;
}
public static void main(String[] args) {
String token = "lF4inzg0SYpt7VekJEhCRYi/hLaPtxgGpflBo5ocWv7lZT09tD+zP8cqTICzTqT8R4raZ3USzv" +
"nyi6tBcE6hNtdoXa8Cq6ub8AZbyoMB0RMWyPbcaKvnbX34kLRnskUECjEKsBRNpYEVP1rNcSVc+" +
"xmDGC7PtcYV+kIRDp5Dmqhcb/7wOHkqyUemTbvhmgb6wgLXE4pdB6NyJZ7JAbfZ5DiIgyGQ7EK4" +
"7hdb4bGn1/15+M4C3OlpOcp7PuFzBuDO1HRkoLXeayFhMKoLHBj1s0wWaFHbPQIYxpCBFW6lzdO" +
"6rVVuhA1YoaoKNZOnYk9fVZ+vQUj5nY2i4yH8u4GJKw==";
String token2="iljUgme83Rj3dCvhFHwFdBB+DXkPpmxTjSFGlsjJJeXQRmQRP62lO9lNYGBkz827TPOjrycRg0BuPLH4I497iuMo7LUMt0mg3C7B3ejRkgcqWoiQxaSjB79mQa8lip/w6Q9S74Wwim/tDw/horrQ/a50+sTe+UYuHh1hjwnr61KQwieNDRFC3rYxeA5WkwpMCVQMHWfTqK3mPjXHqJgoMySUekg0NCbYQYmqWsgetakUuSlaKmrjpK90WfjOsnIeuTWEYHh+tlrI3VVIGF/Pknw6xzLOG+rTi1IZ7RkuHKh8nbiR4uLDkXpvGiiL1Hiq3H2Sz897MZKs1HeqWdrMng==";
// System.out.println(System.getProperty("user.dir"));
String str = decryptRSA(token2);
String encryptText = str + "|" + "298315";
String retStr = encryptRSA(encryptText);
System.out.println("解密后的数据:"+str);
System.out.println("加上PIN加密的数据:"+retStr);
}
}
package com.library.TopUp.mefont;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.library.TopUp.Http.HttpUtils;
import com.library.TopUp.Http.HttpsTool;
import com.library.TopUp.model.ResultsModel;
import org.apache.http.util.TextUtils;
import java.util.HashMap;
import java.util.Map;
public class MetfoneSentUtils {
private final static String baseUrl = "https://36.37.242.116:8301/";
// private final static String baseUrl = "https://payment.emoney.com.kh:8888/";
private final static String PIN = "298315";
public static String initTel(String transAmount, String refId, String customerPhoneNumber) {
Map params = new HashMap();
params.put("serviceType", "TOPUP");
params.put("transAmount", transAmount);
params.put("currency", "USD");
params.put("refId", refId);
params.put("customerPhoneNumber", customerPhoneNumber);
Map<String, String> heardMap = new HashMap<>();
heardMap.put("Authorization", "epa 2478e27af578e11a6af86a8320562124240f5c972e8039cd9c564e53d643bb31");
heardMap.put("e-language", "English");
heardMap.put("Content-Type", "application/json");
heardMap.put("Accept", "application/json");
String url = baseUrl + "ePayTest/telco/init";
// String urlTest="https://36.37.242.116:8301/ePayTest/telco/init";
String str = HttpUtils.post(url,
params, heardMap
, 3000, 3000, "UTF-8");
return str;
}
public static String confirmTel(String txPaymentTokenId) {
Map<String, String> heardMap = new HashMap<>();
heardMap.put("Authorization", "epa 2478e27af578e11a6af86a8320562124240f5c972e8039cd9c564e53d643bb31");
heardMap.put("e-language", "English");
heardMap.put("Content-Type", "application/json");
heardMap.put("Accept", "application/json");
Map params = new HashMap();
params.put("txPaymentTokenId", txPaymentTokenId);
String conURL = baseUrl + "ePayTest/telco/confirm";
String str = HttpUtils.post(conURL,
params, heardMap
, 3000, 3000, "UTF-8");
return str;
}
public static String initTelPost(String transAmount, String refId, String customerPhoneNumber) {
try {
// Map params = new HashMap();
Map<String, String> params = new HashMap<>();
params.put("serviceType", "TOPUP");
params.put("transAmount", transAmount);
params.put("currency", "USD");
params.put("refId", refId);
params.put("customerPhoneNumber", customerPhoneNumber);
Map<String, String> heardMap = new HashMap<>();
heardMap.put("Authorization", "epa 2478e27af578e11a6af86a8320562124240f5c972e8039cd9c564e53d643bb31");
heardMap.put("e-language", "English");
heardMap.put("Content-Type", "application/json");
heardMap.put("Accept", "application/json");
String requestUrl = baseUrl + "ePayTest/telco/init";
String str = HttpsTool.send(new Gson().toJson(params), heardMap, requestUrl, "utf-8",
"utf-8", 300 * 1000, 300 * 1000,
"application/json");// 大家最终只要使用这一句代码就可调用
return str;
} catch (Exception e) {
e.getLocalizedMessage();
return null;
}
}
public static String confirmPost(String txPaymentTokenId) {
try {
Map<String, String> heardMap = new HashMap<>();
heardMap.put("Authorization", "epa 2478e27af578e11a6af86a8320562124240f5c972e8039cd9c564e53d643bb31");
heardMap.put("e-language", "English");
heardMap.put("Content-Type", "application/json");
heardMap.put("Accept", "application/json");
Map params = new HashMap();
params.put("txPaymentTokenId", txPaymentTokenId);
String conURL = baseUrl + "ePayTest/telco/confirm";
String senc = HttpsTool.send(new Gson().toJson(params), heardMap, conURL, "utf-8",
"utf-8", 300 * 1000, 300 * 1000, "application/json");// 大家最终只要使用这一句代码就可调用
return senc;
} catch (Exception e) {
e.getLocalizedMessage();
return null;
}
}
public static String checkPayPost(String transDetailId, String refId) {
try {
Map<String, String> heardMap = new HashMap<>();
heardMap.put("Authorization", "epa 2478e27af578e11a6af86a8320562124240f5c972e8039cd9c564e53d643bb31");
heardMap.put("e-language", "English");
heardMap.put("Content-Type", "application/json");
heardMap.put("Accept", "application/json");
Map params = new HashMap();
params.put("transDetailId", transDetailId);
params.put("refId", refId);
String conURL = baseUrl + "ePayTest/trans/check";
String senc = HttpsTool.send(new Gson().toJson(params), heardMap, conURL, "utf-8",
"utf-8", 300 * 1000, 300 * 1000, "application/json");// 大家最终只要使用这一句代码就可调用
return senc;
} catch (Exception e) {
e.getLocalizedMessage();
return null;
}
}
public static String billInfoPost(String paymentCode) {
try {
Map<String, String> heardMap = new HashMap<>();
heardMap.put("Authorization", "epa 2478e27af578e11a6af86a8320562124240f5c972e8039cd9c564e53d643bb31");
heardMap.put("e-language", "English");
heardMap.put("Content-Type", "application/json");
heardMap.put("Accept", "application/json");
Map params = new HashMap();
params.put("paymentCode", paymentCode);
String conURL = baseUrl + "ePayTest/telco/metfone-bill/info";
String senc = HttpsTool.send(new Gson().toJson(params), heardMap, conURL, "utf-8",
"utf-8", 300 * 1000, 300 * 1000, "application/json");// 大家最终只要使用这一句代码就可调用
return senc;
} catch (Exception e) {
e.getLocalizedMessage();
return null;
}
}
/**
* 查询系统我的账户余额
*
* @param refId
* @param msisdn
* @return
*/
public static String checkMyMoneyPost(String refId, String msisdn) {
try {
Map<String, String> heardMap = new HashMap<>();
heardMap.put("Authorization", "epa 2478e27af578e11a6af86a8320562124240f5c972e8039cd9c564e53d643bb31");
heardMap.put("e-language", "English");
heardMap.put("Content-Type", "application/json");
heardMap.put("Accept", "application/json");
String pin = PIN + "|" + msisdn + "|" + refId;
Map params = new HashMap();
params.put("refId", refId);
params.put("serviceType", "TOPUP");
params.put("msisdn", msisdn);
params.put("pin", MetfoneRSAUtils.encryptRSA(pin));//encrypt the plain text in format "pin|msisdn|refId
String conURL = baseUrl + "ePayTest/account/balance";
String senc = HttpsTool.send(new Gson().toJson(params), heardMap, conURL, "utf-8",
"utf-8", 300 * 1000, 300 * 1000,
"application/json");// 大家最终只要使用这一句代码就可调用
return senc;
} catch (Exception e) {
e.getLocalizedMessage();
return null;
}
}
public static void main2222(String[] args) {
/* String str = checkMyMoneyPost("1200016", "0979530750");
//{"status":0,"code":"MSG_SUCCESS","message":"Success","msisdn":null,"accountName":null,"accountType":null,"balances":{"KHR":"498,983","USD":"5,135.60"}}
System.out.println(str);*/
/* String str = billInfoPost("0979530750");
System.out.println(str);*/
}
public static void main(String[] args) {
String phone = "0979530750";
ResultsModel resultsModel=sentTopUp(phone, 1, "123124");
System.out.println("充值日志:"+resultsModel.getTip());
System.out.println("充值状态:"+resultsModel.isSuccessful());
System.out.println("拓展字段:"+resultsModel.getExpandText());
}
/**
* 发起充值
*
* @param phone
* @param amount
* @param orderNum
* @return
*/
public static ResultsModel sentTopUp(String phone, int amount, String orderNum) {
String tip = "";
boolean topUpSuccess = false;
try {
String refId = orderNum;
String transDetailId = "";//可以用来复查充值订单数据
String json = initTelPost(String.valueOf(amount), refId, phone);
String tokenId = "";
if (!TextUtils.isEmpty(json)) {
JsonObject object = new JsonParser().parse(json).getAsJsonObject();
String status = object.get("status") == null ? "" : object.get("status").getAsString();
//请求是否成功
if (status.equals("0")) {
JsonObject txDetail = object.get("txDetail").getAsJsonObject();
if (txDetail != null) {
//获取需要解密的值
tokenId = txDetail.get("txPaymentTokenId").getAsString();
transDetailId = txDetail.get("transDetailId").getAsString();
} else {
tip += "返回值txDetail为空";
}
} else {
tip += "initTel返回结果:" + new Gson().toJson(object) + " \n";
}
} else {
tip += "返回值为空";
}
String conStr = "";
if (!TextUtils.isEmpty(tokenId)) {
String str = MetfoneRSAUtils.decryptRSA(tokenId);
String encryptText = str + "|" + PIN;
// tip += "解析的值:" + encryptText;
String retStr = MetfoneRSAUtils.encryptRSA(encryptText);
// tip += "\n" + "加密后的值:" + retStr;
//发起充值
conStr = confirmPost(retStr);
}
//处理返回结果
if (!TextUtils.isEmpty(conStr)) {
//有结果返回
System.out.println(conStr);
JsonObject confirmObject = new JsonParser().parse(conStr).getAsJsonObject();
String status = confirmObject.get("status") == null ? "" : confirmObject.get("status").getAsString();
if (status.equals("0")) {
System.out.println("充值成功");
topUpSuccess = true;
tip += " 充值成功!!!";
} else {
tip += "confirmTel返回结果:" + new Gson().toJson(confirmObject) + " \n";
}
}
// String checkStr = checkPayPost(transDetailId, refId);
// System.out.println(checkStr);
return new ResultsModel(topUpSuccess, tip, transDetailId);
} catch (Exception e) {
e.printStackTrace();
return new ResultsModel(topUpSuccess, tip);
}
}
}
MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCY6EbOULc7ksASsPnO3mKj21tBIeuw2BBI+56OesX45qbEbs4pRzpqzPcj65jgHmSEfYwa5JNGcmGi3JD4ixJFIQzyUvmk+7XZUint04rMyYzrzKHeUcTv/jZ5P0Z/vqXSgFzaciDdnG2K159IjNt/adedcDVPQJ7q6D7qm94LaghTQh9rA1PXF7L1zVne5G51llAuY2FKUt0HXp4W5ZhcqgpiLlalKPYPNfwACkbkREmse9ibjvpIfEsg5USw1wFuqRG0FarZNO6y8iTVj1wZSob33/BG2FhGVUxyUGLN0mS1lfCFU3aitrgdkeoLSRfq8zi/mEk4n6kk4u/YHM1nAgMBAAECggEAKmXdnD+NTxt13rjry4ymVUDxoLHDJJoEifgbEu7ADjAGddkzmQaDEDIdJPyiuyIyRPp66soOfC4jHIGEQSZuvnRXnqmbRz/0QHoj3ioWBoqsZIWtLHQH43Pdruj4p1s5p5CoLnoO2uQRC7qWFAvaoQ28F4+ReJQ2fHRBXdQyUX97PzQszZyAQWc/9UbUEyeZim9xl+SRKssP0u5d5Duh/2CTieZbOXh+4lLe1/mv2aXtSQCFiW8wgWXYJE03q8kSediKwuxfG//Dj5+oR6dz96wyLLao94HemRFNYZq8CoJs5z1eyuj2QYxQGgEhZJYTyl0hDK7+JwSNPldLtOae4QKBgQDRvmocabHoCUYKgjJKCtSAfSF+y/U5iwDsH1FZYhp8ZxkBuALWVD2FhtuZYbGvzDYuYSpLa/VITRR5yBTUXuhLNSPUOIDLS3Ba9V38SdxsWKSgBkTRdE6O9ShkEQfBMQ0v17JTfATCn7lUTRCqV3ayAkfJNqVh+TpZWCI5u/SsywKBgQC6oQYMyPMCAeTMSHVYJ4WUWDz5ZxOyqQCIvicQtunJ7U2Y/+iY8ZQl1B6jJ/JColBjxqTqFIq8LFdJD7VkE+/AKFjwr0RgTy2tRqJNvyaSrIdVi/6OI+y1RXS4VBiY+SZ5wobx1v1t7se4ltdN71Xbuzz/QmXDCtbMPLam8u6KVQKBgQCb1H/buj9eaL1sA00/q4o0KEOhhAEejoLR63ayFOwery5qE3+wI4hN02MGMwoj1XIPxUr6HCxxWiszS48GNbkaX1HOU2iFIfhI6/G3Bl1I9hbheabZgzL2jXhD2E9Nnpbwi63GzuZufuLfmh4eoLrkCEOzX/FBuDw8svlCsb1YPwKBgFgfKj0lMWFURZWT7RyH5NIL7BaTbkCg/iiTKN0CkVeQXmCNDWYSQ7Ks+x5tAT4naDAEnuAMfQmnIjvUWAD+TOl946kaCP40xMuZm498X5lIL8rcBIFXQzDAsAFNbCPnGRzLFm7g5d9frRxi1RzukqrjOUUKNASpfI0JafFgqfPVAoGAI1Oz2PsG4phr8USI7cB1P0mVOc+69tn6QA/oDT8dBqO9bVuBRuQsVgoPPKTbusK1Na0NDmMAfgwRynxPCwwSevGiWlCGFZGj+eM9a52g6BbbHT2LGsQqWsLINFBOAwUAPoyOyB76EC1iQ2FM/mvQbBwnsNaG6SZX73dchlkn7iU=
\ No newline at end of file
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAn0dF9WwFY8Te4AEoGdTC34c9vStRegi9D9H4jXXNoOAMyRPH+e9I+ZTJfERpIs45j+Y+KezmI0bFJ/mk06ZK9Si9V81aeBsgtgy5Ul4reQYkH9KL0G7hboX1eePkmc95qCQFwGD3PEITKD6ei43YxYfOf8BltHFZ0Z+opkTTZHW5aOMAFUIRoaXTpaVD+I7rx6gDJX+pZsPowLpfFjGAY2YRe2FJN1YXtyJFEDhRJDeqY4QakelyKGDK8gi5CFLxDtkUxpF3QWUk98WLJH/mkGJUmKAORksVR7ReaHbEWQkJUuDUxh0YUr9X7aXGZnbHAuDTbUqCP4L/wFBIhWWaOwIDAQAB
\ No newline at end of file
package com.library.TopUp.mefont.model;
public class InitModel {
private String serviceType;
private String transAmount;
private String currency;
private String refId;
private String customerPhoneNumber;
public String getServiceType() {
return serviceType;
}
public void setServiceType(String serviceType) {
this.serviceType = serviceType;
}
public String getTransAmount() {
return transAmount;
}
public void setTransAmount(String transAmount) {
this.transAmount = transAmount;
}
public String getCurrency() {
return currency;
}
public void setCurrency(String currency) {
this.currency = currency;
}
public String getRefId() {
return refId;
}
public void setRefId(String refId) {
this.refId = refId;
}
public String getCustomerPhoneNumber() {
return customerPhoneNumber;
}
public void setCustomerPhoneNumber(String customerPhoneNumber) {
this.customerPhoneNumber = customerPhoneNumber;
}
}
package com.library.TopUp.mefont.model;
public class MetfoneResultsModel {
private boolean isSuccessful;
private String tip;
}
package com.library.TopUp.model;
public class ResultsModel {
private boolean isSuccessful;
private String tip;
private String expandText;
public ResultsModel(boolean isSuccessful, String tip) {
this.isSuccessful = isSuccessful;
this.tip = tip;
}
public ResultsModel(boolean isSuccessful, String tip, String expandText) {
this.isSuccessful = isSuccessful;
this.tip = tip;
this.expandText = expandText;
}
public ResultsModel() {
}
public boolean isSuccessful() {
return isSuccessful;
}
public void setSuccessful(boolean successful) {
isSuccessful = successful;
}
public String getTip() {
return tip;
}
public void setTip(String tip) {
this.tip = tip;
}
public String getExpandText() {
return expandText;
}
public void setExpandText(String expandText) {
this.expandText = expandText;
}
}
package com.library.TopUp.smart;
import java.io.Serializable;
/**
* Description: 封装httpClient响应结果
*
* @author JourWon
* @date Created on 2018年4月19日
*/
public class HttpClientResult implements Serializable {
public HttpClientResult(){
}
public HttpClientResult(int code) {
this.code = code;
this.content = "";
}
public HttpClientResult(int code, String content) {
this.code = code;
this.content = content;
}
/**
* 响应状态码
*/
private int code;
/**
* 响应数据
*/
private String content;
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
}
package com.library.TopUp.smart;
import net.sf.json.JSONObject;
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.*;
import org.apache.http.client.utils.URIBuilder;
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.message.BasicHeader;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import java.io.*;
import java.util.*;
/**
* Description: httpClient工具类
*
* @author JourWon
* @date Created on 2018年4月19日
*/
public class HttpClientUtils {
// 编码格式。发送编码格式统一用UTF-8
private static final String ENCODING = "UTF-8";
// 设置连接超时时间,单位毫秒。
private static final int CONNECT_TIMEOUT = 6000;
// 请求获取数据的超时时间(即响应时间),单位毫秒。
private static final int SOCKET_TIMEOUT = 6000;
/**
* 发送get请求;不带请求头和请求参数
*
* @param url 请求地址
* @return
* @throws Exception
*/
public static HttpClientResult doGet(String url) throws Exception {
return doGet(url, null, null);
}
/**
* 发送get请求;带请求参数
*
* @param url 请求地址
* @param params 请求参数集合
* @return
* @throws Exception
*/
public static HttpClientResult doGet(String url, Map<String, String> params) throws Exception {
return doGet(url, null, params);
}
/**
* 发送get请求;带请求头和请求参数
*
* @param url 请求地址
* @param headers 请求头集合
* @param params 请求参数集合
* @return
* @throws Exception
*/
public static HttpClientResult doGet(String url, Map<String, String> headers, Map<String, String> params) throws Exception {
// 创建httpClient对象
CloseableHttpClient httpClient = HttpClients.createDefault();
// 创建访问的地址
URIBuilder uriBuilder = new URIBuilder(url);
if (params != null) {
Set<Map.Entry<String, String>> entrySet = params.entrySet();
for (Map.Entry<String, String> entry : entrySet) {
uriBuilder.setParameter(entry.getKey(), entry.getValue());
}
}
// 创建http对象
HttpGet httpGet = new HttpGet(uriBuilder.build());
/**
* setConnectTimeout:设置连接超时时间,单位毫秒。
* setConnectionRequestTimeout:设置从connect Manager(连接池)获取Connection
* 超时时间,单位毫秒。这个属性是新加的属性,因为目前版本是可以共享连接池的。
* setSocketTimeout:请求获取数据的超时时间(即响应时间),单位毫秒。 如果访问一个接口,多少时间内无法返回数据,就直接放弃此次调用。
*/
RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(CONNECT_TIMEOUT).setSocketTimeout(SOCKET_TIMEOUT).build();
httpGet.setConfig(requestConfig);
// 设置请求头
packageHeader(headers, httpGet);
// 创建httpResponse对象
CloseableHttpResponse httpResponse = null;
try {
// 执行请求并获得响应结果
return getHttpClientResult(httpResponse, httpClient, httpGet);
} finally {
// 释放资源
release(httpResponse, httpClient);
}
}
/**
* 发送post请求;不带请求头和请求参数
*
* @param url 请求地址
* @return
* @throws Exception
*/
public static HttpClientResult doPost(String url) throws Exception {
return doPost(url, null, null);
}
/**
* 发送post请求;带请求参数
*
* @param url 请求地址
* @param params 参数集合
* @return
* @throws Exception
*/
public static HttpClientResult doPost(String url, Map<String, String> params) throws Exception {
return doPost(url, null, params);
}
/**
* 发送post请求;带请求头和请求参数
*
* @param url 请求地址
* @param headers 请求头集合
* @param params 请求参数集合
* @return
* @throws Exception
*/
public static HttpClientResult doPost(String url, Map<String, String> headers, Map<String, String> params) throws Exception {
// 创建httpClient对象
CloseableHttpClient httpClient = HttpClients.createDefault();
// 创建http对象
HttpPost httpPost = new HttpPost(url);
/**
* setConnectTimeout:设置连接超时时间,单位毫秒。
* setConnectionRequestTimeout:设置从connect Manager(连接池)获取Connection
* 超时时间,单位毫秒。这个属性是新加的属性,因为目前版本是可以共享连接池的。
* setSocketTimeout:请求获取数据的超时时间(即响应时间),单位毫秒。 如果访问一个接口,多少时间内无法返回数据,就直接放弃此次调用。
*/
RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(CONNECT_TIMEOUT).setSocketTimeout(SOCKET_TIMEOUT).build();
httpPost.setConfig(requestConfig);
// 设置请求头
/*httpPost.setHeader("Cookie", "");
httpPost.setHeader("Connection", "keep-alive");
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Accept-Language", "zh-CN,zh;q=0.9");
httpPost.setHeader("Accept-Encoding", "gzip, deflate, br");
httpPost.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36");*/
packageHeader(headers, httpPost);
System.out.println("URL: " + url);
// 封装请求参数
packageParam(params, httpPost);
// 创建httpResponse对象
CloseableHttpResponse httpResponse = null;
try {
// 执行请求并获得响应结果
return getHttpClientResult(httpResponse, httpClient, httpPost);
} finally {
// 释放资源
release(httpResponse, httpClient);
}
}
/**
* 发送put请求;不带请求参数
*
* @param url 请求地址
* @return
* @throws Exception
*/
public static HttpClientResult doPut(String url) throws Exception {
return doPut(url);
}
/**
* 发送put请求;带请求参数
*
* @param url 请求地址
* @param params 参数集合
* @return
* @throws Exception
*/
public static HttpClientResult doPut(String url, Map<String, String> params) throws Exception {
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpPut httpPut = new HttpPut(url);
RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(CONNECT_TIMEOUT).setSocketTimeout(SOCKET_TIMEOUT).build();
httpPut.setConfig(requestConfig);
packageParam(params, httpPut);
CloseableHttpResponse httpResponse = null;
try {
return getHttpClientResult(httpResponse, httpClient, httpPut);
} finally {
release(httpResponse, httpClient);
}
}
/**
* 发送delete请求;不带请求参数
*
* @param url 请求地址
* @return
* @throws Exception
*/
public static HttpClientResult doDelete(String url) throws Exception {
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpDelete httpDelete = new HttpDelete(url);
RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(CONNECT_TIMEOUT).setSocketTimeout(SOCKET_TIMEOUT).build();
httpDelete.setConfig(requestConfig);
CloseableHttpResponse httpResponse = null;
try {
return getHttpClientResult(httpResponse, httpClient, httpDelete);
} finally {
release(httpResponse, httpClient);
}
}
/**
* 发送delete请求;带请求参数
*
* @param url 请求地址
* @param params 参数集合
* @return
* @throws Exception
*/
public static HttpClientResult doDelete(String url, Map<String, String> params) throws Exception {
if (params == null) {
params = new HashMap<String, String>();
}
params.put("_method", "delete");
return doPost(url, params);
}
/**
* Description: 封装请求头
*
* @param params
* @param httpMethod
*/
public static void packageHeader(Map<String, String> params, HttpRequestBase httpMethod) {
// 封装请求头
if (params != null) {
Set<Map.Entry<String, String>> entrySet = params.entrySet();
for (Map.Entry<String, String> entry : entrySet) {
// 设置到请求头到HttpRequestBase对象中
httpMethod.setHeader(entry.getKey(), entry.getValue());
}
}
}
/**
* Description: 封装请求参数
*
* @param params
* @param httpMethod
* @throws UnsupportedEncodingException
*/
public static void packageParam(Map<String, String> params, HttpEntityEnclosingRequestBase httpMethod)
throws UnsupportedEncodingException {
// 封装请求参数
if (params != null) {
List<NameValuePair> nvps = new ArrayList<NameValuePair>();
Set<Map.Entry<String, String>> entrySet = params.entrySet();
for (Map.Entry<String, String> entry : entrySet) {
nvps.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
System.out.println("" + entry.getKey() + " : " + entry.getValue());
}
// 设置到请求的http对象中
httpMethod.setEntity(new UrlEncodedFormEntity(nvps, ENCODING));
}
}
/**
* Description: 获得响应结果
*
* @param httpResponse
* @param httpClient
* @param httpMethod
* @return
* @throws Exception
*/
public static HttpClientResult getHttpClientResult(CloseableHttpResponse httpResponse,
CloseableHttpClient httpClient, HttpRequestBase httpMethod) throws Exception {
// 执行请求
httpResponse = httpClient.execute(httpMethod);
// 获取返回结果
if (httpResponse != null && httpResponse.getStatusLine() != null) {
String content = "";
if (httpResponse.getEntity() != null) {
content = EntityUtils.toString(httpResponse.getEntity(), ENCODING);
}
return new HttpClientResult(httpResponse.getStatusLine().getStatusCode(), content);
}
return new HttpClientResult(HttpStatus.SC_INTERNAL_SERVER_ERROR);
}
/**
* Description: 释放资源
*
* @param httpResponse
* @param httpClient
* @throws IOException
*/
public static void release(CloseableHttpResponse httpResponse, CloseableHttpClient httpClient) throws IOException {
// 释放资源
if (httpResponse != null) {
httpResponse.close();
}
if (httpClient != null) {
httpClient.close();
}
}
public static String postWithJson(String json, String URL, Map<String, String> headers) {
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(URL);
String result = "";
//加入请求头
packageHeader(headers, post);
try {
StringEntity s = new StringEntity(json, "utf-8");
s.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,
"application/json"));
post.setEntity(s);
// 发送请求
HttpResponse httpResponse = client.execute(post);
// 获取响应输入流
InputStream inStream = httpResponse.getEntity().getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(
inStream, "utf-8"));
StringBuilder strber = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
strber.append(line + "\n");
inStream.close();
result = strber.toString();
// System.out.println(result);
System.out.println(httpResponse.getStatusLine().getStatusCode() + " ==== " + HttpStatus.SC_OK);
if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK || httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_CREATED) {
System.out.println("请求服务器成功,做相应处理");
} else {
System.out.println("请求服务端失败");
}
} catch (Exception e) {
System.out.println("请求异常");
throw new RuntimeException(e);
}
return result;
}
}
package com.library.TopUp.smart;
import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.library.TopUp.Http.HttpUtils;
import com.library.TopUp.Http.HttpsTool;
import com.library.TopUp.model.ResultsModel;
import net.sf.json.JSONObject;
import org.apache.http.util.TextUtils;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
public class SmartSentUtils {
private static String access_token = "";
private static String refresh_token = "";
private static String token_type = "";
private static int expires_in;
private final static String institution_id = "98198198";
private final static String institution_password = "OTgxOTgxOTg=";
public static String getToken() {
try {
Map params = new HashMap();
params.put("grant_type", "password");
params.put("username", "link.asia");
params.put("password", "@@$$SSaa_8899");
Map<String, String> heardMap = new HashMap<>();
heardMap.put("Authorization", "Basic R21GcTFqU0haMG0yNkttVU5IX2sxam1xdElvYTp1elZWdjdObkRhVEtZNm9PZnhneWUwOHJCNGdh");
heardMap.put("Content-Type", "application/x-www-form-urlencoded");
heardMap.put("Accept", "application/json");
String url = "https://mife.smart.com.kh:8243/token";
HttpClientResult clientResult = HttpClientUtils.doPost(url, heardMap, params);
// String str = HttpUtils.post(url,
// params, heardMap
// , 3000, 3000, "UTF-8");
return clientResult.getContent();
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public static String refreshToken(String refresh_token) {
try {
Map params = new HashMap();
params.put("grant_type", "refresh_token");
params.put("refresh_token", refresh_token);
Map<String, String> heardMap = new HashMap<>();
heardMap.put("Authorization", "Basic R21GcTFqU0haMG0yNkttVU5IX2sxam1xdElvYTp1elZWdjdObkRhVEtZNm9PZnhneWUwOHJCNGdh");
heardMap.put("Content-Type", "application/x-www-form-urlencoded");
heardMap.put("Accept", "application/json");
String url = "https://mife.smart.com.kh:8243/token";
HttpClientResult clientResult = HttpClientUtils.doPost(url, heardMap, params);
return clientResult.getContent();
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public static String checkPhone(String phone) {
try {
String phoneStr = "tel:+855" + phone;
String endPhone = URLEncoder.encode(phoneStr);
Map params = new HashMap();
Map<String, String> heardMap = new HashMap<>();
heardMap.put("Authorization", token_type + " " + access_token);
heardMap.put("Content-Type", "application/x-www-form-urlencoded");
heardMap.put("Accept", "application/json");
String url = "https://mife.smart.com.kh:8243/api/etopup/pinless/v1.1/" + endPhone + "/eligibility";
HttpClientResult clientResult = HttpClientUtils.doGet(url, heardMap, params);
return clientResult.getContent();
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public static String rechargePhone(String phone, String amount, String correlation_id) {
try {
String phoneStr = "tel:+855" + phone;
String endPhone = URLEncoder.encode(phoneStr);
Map<String, String> heardMap = new HashMap<>();
heardMap.put("Authorization", token_type + " " + access_token);
heardMap.put("Content-Type", "application/json");
heardMap.put("Accept", "application/json");
Map<String, String> params = new HashMap();
params.put("institution_password", institution_password);
params.put("correlation_id", correlation_id);
params.put("amount", amount);
params.put("channel", "WEB");
String url = "https://mife.smart.com.kh:8243/api/etopup/pinless/v1.1/" + institution_id + "/recharge/" + endPhone + "";
String json = HttpClientUtils.postWithJson(new Gson().toJson(params), url, heardMap);
// String json = HttpsTool.send(new Gson().toJson(params), heardMap, url, "utf-8",
// "utf-8", 30 * 1000, 30 * 1000, "application/json");// 大家最终只要使用这一句代码就可调用
return json;
// return clientResult.getContent();
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public static String queryRechargePhone(String correlation_id) {
try {
String end_correlation_id = URLEncoder.encode(correlation_id);
Map<String, String> params = new HashMap();
params.put("institution_password", institution_password);
Map<String, String> heardMap = new HashMap<>();
heardMap.put("Authorization", token_type + " " + access_token);
heardMap.put("Content-Type", "application/json");
heardMap.put("Accept", "application/json");
String url = "https://mife.smart.com.kh:8243/api/etopup/pinless/v1.1/" + institution_id + "/query/" + end_correlation_id + "";
String json = HttpClientUtils.postWithJson(new Gson().toJson(params), url, heardMap);
return json;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public static void main2222(String[] args) {
String json = getToken();
// //{"access_token":"372b5f81-9662-3d75-abcf-639920880ce3","refresh_token":"d62d9da3-3730-35f7-9368-c82b43509db1","scope":"default","token_type":"Bearer","expires_in":3249}//
System.out.println(json);
String tip = "";
if (!TextUtils.isEmpty(json)) {
JsonParser jsonParser = new JsonParser();
JsonObject jsonObject = jsonParser.parse(json).getAsJsonObject();
String token = jsonObject.get("access_token").getAsString();
if (!TextUtils.isEmpty(token)) {
access_token = token;
refresh_token = jsonObject.get("refresh_token").getAsString();
token_type = jsonObject.get("token_type").getAsString();
expires_in = jsonObject.get("expires_in").getAsInt();
} else {
tip += "返回结果:" + json;
}
} else {
tip += "返回值为空";
}
System.out.println(tip);
String jsonQuery = queryRechargePhone("58cam:87234159:100025");
System.out.println(jsonQuery);
if (!TextUtils.isEmpty(jsonQuery)) {
JsonParser jsonQueryParser = new JsonParser();
JsonObject jsonObjectQuery = jsonQueryParser.parse(jsonQuery).getAsJsonObject();
String recharge_status = jsonObjectQuery.get("recharge_status").getAsString();
if (recharge_status.equals("Succeeded")) {
System.out.println("充值成功");
}
}
}
public static void main(String[] args) {
String phone = "87234159";
ResultsModel resultsModel = sentTopUp(phone, 1, "99999912");
System.out.println("充值是否成功:" + resultsModel.isSuccessful());
System.out.println("充值日志:" + resultsModel.getTip());
}
/**
* 发送Smart充值请求
*
* @param phone 手机号
* @param topUpAmount 单位1美元,里面已经做了1分钱转1元的处理了
* @param orderNum 需要确保唯一性,建议使用订单id
*/
public static ResultsModel sentTopUp(String phone, int topUpAmount, String orderNum) {
String tip = "";
boolean topUpSuccess = false;
try {
String json = getToken();
/**
* {"access_token":"372b5f81-9662-3d75-abcf-639920880ce3","refresh_token":"d62d9da3-3730-35f7-9368-c82b43509db1","scope":"default","token_type":"Bearer","expires_in":3249}//
*/
System.out.println(json);
String tokenStr = "";
//判断是否成功获取到token
if (!TextUtils.isEmpty(json)) {
JsonParser jsonParser = new JsonParser();
JsonObject jsonObject = jsonParser.parse(json).getAsJsonObject();
tokenStr = jsonObject.get("access_token") == null ? "" : jsonObject.get("access_token").getAsString();
if (!TextUtils.isEmpty(tokenStr)) {
access_token = tokenStr;
refresh_token = jsonObject.get("refresh_token").getAsString();
token_type = jsonObject.get("token_type").getAsString();
expires_in = jsonObject.get("expires_in").getAsInt();
} else {
tip += " 返回结果:" + json;
}
} else {
tip += " 返回值为空";
}
System.out.println(tip);
String phoneJson = "";
if (!TextUtils.isEmpty(tokenStr)) {
//成功获取到token,可以进行校验手机号了
phoneJson = checkPhone(phone);
System.out.println(phoneJson);
}
String correlation_id = "";
// String refJson = refreshToken("d62d9da3-3730-35f7-9368-c82b43509db1");
// System.out.println(refJson);
//手机号校验是否成功,如果成功,则直接发起充值
if (!TextUtils.isEmpty(phoneJson)) {
JsonParser jsonParser2 = new JsonParser();
JsonObject jsonObject2 = jsonParser2.parse(phoneJson).getAsJsonObject();
String eligible = jsonObject2.get("eligible") == null ? "" : jsonObject2.get("eligible").getAsString();
if (eligible.equals("true")) {
//校验成功
tip += " 手机号码校验成功 !!!";
String rechId = "58cam:" + phone + ":" + orderNum;
int amount = topUpAmount * 100;//需要乘以100,文档写在至少100分美元,则1美元,以分为单位
String rechargeJson = rechargePhone(phone, String.valueOf(amount), rechId);//发起充值
System.out.println(rechargeJson);
/*
* {
"correlation_id": "58cam:87234159:100025",
"institution_id": "98198198",
"subscriber_id": "tel:+85587234159",
"amount": 100,
"channel": "WEB",
"instance_id": "0106142011016656"
}
* */
if (!TextUtils.isEmpty(rechargeJson)) {
JsonParser jsonParserRecharge = new JsonParser();
JsonObject jsonObjectRecharge = jsonParserRecharge.parse(rechargeJson).getAsJsonObject();
correlation_id = jsonObjectRecharge.get("correlation_id") == null ? "" : jsonObjectRecharge.get("correlation_id").getAsString();//不为空,则充值成功
tip += " 充值发起成功!!!";
} else {
tip += " 充值请求返回值为空;";
}
} else {
//手机号码校验失败
tip += " 手机号码校验失败,返回值:" + phoneJson;
}
} else {
tip += " 手机号码校验返回值为空;";
}
String jsonQuery = "";
//如果充值成功,可以进行校验充值状态
if (!TextUtils.isEmpty(correlation_id)) {
//充值成功了
topUpSuccess = true;
tip += " 充值成功,发起复查;";
jsonQuery = queryRechargePhone(correlation_id);//发起校验
System.out.println(jsonQuery);
//校验复查充值是否成功
if (!TextUtils.isEmpty(jsonQuery)) {
JsonParser jsonQueryParser = new JsonParser();
JsonObject jsonObjectQuery = jsonQueryParser.parse(jsonQuery).getAsJsonObject();
String recharge_status = jsonObjectQuery.get("recharge_status") == null ? "" : jsonObjectQuery.get("recharge_status").getAsString();
if (recharge_status.equals("Succeeded")) {
System.out.println(" 复查充值成功!!");
tip += " 复查充值结果:成功。";
} else {
tip += " 复查充值结果:" + jsonQuery;
}
} else {
tip += " 复查充值结果为空;";
}
}
System.out.println(tip);
ResultsModel resultsModel = new ResultsModel(topUpSuccess, tip);
return resultsModel;
} catch (Exception e) {
e.printStackTrace();
ResultsModel resultsModel = new ResultsModel(topUpSuccess, tip);
return resultsModel;
}
}
}
......@@ -20,6 +20,7 @@ public class NameValue {
public static String Table_automatic_queue = "pre_dz_pay_automatic_queue";//充值队列表
public static String Table_order_log = "pre_dz_pay_order_log";//订单日志表
public static String Table_order = "pre_dz_pay_order";//订单表
public static String Table_pay_segment = "pre_dz_pay_segment";//订单表
......
package com.library.controller;
import com.library.TopUp.cellcard.CellcardSentUtils;
import com.library.respcode.ServerResponse;
import com.library.service.AdminService;
import com.library.service.CommService;
......@@ -11,7 +12,7 @@ import org.springframework.web.bind.annotation.ResponseBody;
import javax.annotation.Resource;
/*
* @项目名: yunVpay
* @项目名: yunVpay
* @包名: com.library.controller
* @文件名: CommonController
* @创建者: zhouzhuo
......@@ -20,7 +21,7 @@ import javax.annotation.Resource;
*/
@Controller
@RequestMapping("/Common")
public class CommonController{
public class CommonController {
@Resource
private CommService commService;
......@@ -29,7 +30,7 @@ public class CommonController{
//获取七牛云的token
@ResponseBody
@RequestMapping("/FindQNYToken")
private ServerResponse FindQNYToken(){
private ServerResponse FindQNYToken() {
String token = QiniuUtils.getUpToken();
return ServerResponse.createBySuccess(token);
}
......@@ -48,4 +49,14 @@ public class CommonController{
return commService.adminLogin();
}
//登录
@ResponseBody
@RequestMapping("test")
private ServerResponse test() {
String json = CellcardSentUtils.getToken();
System.out.println(json);
return ServerResponse.createBySuccess(json);
}
}
......@@ -23,5 +23,12 @@ public interface AutomaticQueueMapper {
*/
public Map<String, Object> selectOrderByNumber(@Param("order_number") String order_number);
/**
* 根据手机前三位获取到运营商数据
* @param phone_three
* @return
*/
public Map<String, Object> selectSegment(@Param("phone_three") String phone_three);
}
......@@ -11,4 +11,8 @@
<select id="selectOrderByNumber" resultType="map" parameterType="map">
select * from pre_dz_pay_order where order_number = #{order_number};
</select>
<select id="selectSegment" resultType="map" parameterType="map">
select * from pre_dz_pay_segment where phone_three = #{phone_three};
</select>
</mapper>
......@@ -43,6 +43,15 @@ public class OrderModel {
private String phone;
private int id;
private int state; //支付结果1.待支付,2支付成功(系统处理中) 3.充值成功 4充值失败(人工处理)
private String top_up_num;
public String getTop_up_num() {
return top_up_num;
}
public void setTop_up_num(String top_up_num) {
this.top_up_num = top_up_num;
}
public int getGid() {
return gid;
......
package com.library.service.Impl;
import com.library.TopUp.cellcard.CellcardSentUtils;
import com.library.TopUp.mefont.MetfoneSentUtils;
import com.library.TopUp.model.ResultsModel;
import com.library.TopUp.smart.SmartSentUtils;
import com.library.config.NameValue;
import com.library.mapper.AutomaticQueueMapper;
import com.library.mapper.CurrencyMapper;
import com.library.model.AutomaticQueueModel;
import com.library.model.OrderLogModel;
import com.library.model.OrderModel;
import com.library.model.SegmentModel;
import com.library.service.AutomaticCodeService;
import com.library.util.Paygo24Utils;
import com.library.util.TransformationTools;
......@@ -80,15 +85,20 @@ public class AutomaticCodeServiceImpl implements AutomaticCodeService {
//添加订单操作日志
currencyMapper.AddTableForMysql(TransformationTools.CreatAddMysql(orderLogModel, NameValue.Table_order_log, "id", null));
// //去充值
// Paygo24Utils paygo = new Paygo24Utils();
// String result = paygo.payment(automaticQueueModel.getOrder_phone(), automaticQueueModel.getSegment_id(), automaticQueueModel.getOrder_money());
// desc = result;//描述
// if (result.equals(Paygo24Utils.SUCCESS)) {
// success = true;
// } else {
// success = false;
// }
//去充值
Paygo24Utils paygo = new Paygo24Utils();
String result = paygo.payment(automaticQueueModel.getOrder_phone(), automaticQueueModel.getSegment_id(), automaticQueueModel.getOrder_money());
desc = result;//描述
if (result.equals(Paygo24Utils.SUCCESS)) {
success = true;
} else {
success = false;
}
ResultsModel resultsModel = sentTopup(automaticQueueModel);
desc = resultsModel.getTip();
success = resultsModel.isSuccessful();
} catch (Exception e) {
e.printStackTrace();
......@@ -98,9 +108,65 @@ public class AutomaticCodeServiceImpl implements AutomaticCodeService {
// 自动处理结果
this.automaticForTackResult(automaticQueueModel, success, desc);
}
}
private final static String SegmentType_Cellcard = "Cellcard";
private final static String SegmentType_Metfone = "Metfone";
private final static String SegmentType_Smart = "Smart";
private final static String SegmentType_Seatel = "Seatel";
private ResultsModel sentTopup(AutomaticQueueModel automaticQueueModel) {
ResultsModel resultsModel = null;
try {
//订单id 统一一下长度八位数
String orderNumId = String.valueOf(automaticQueueModel.getOrder_code_id() + 10000000);
//通过手机前三位获取到运营商
String phoneThree = automaticQueueModel.getOrder_phone().substring(0, 3);
Map<String, Object> map = automaticQueueMapper.selectSegment(phoneThree);
//1.先判断这是哪个公司的充值订单
SegmentModel segmentModel = (SegmentModel) TransformationTools.ToObjectOne(SegmentModel.class, map);
if (segmentModel.getOperator().equals(SegmentType_Cellcard)) {
//Cellcard的手机号,则选择Cellcard公司的api发起充值
resultsModel = CellcardSentUtils.sentTopUp(automaticQueueModel.getOrder_phone(), orderNumId, automaticQueueModel.getOrder_money().intValue());
} else if (segmentModel.getOperator().equals(SegmentType_Metfone)) {
resultsModel = MetfoneSentUtils.sentTopUp(automaticQueueModel.getOrder_phone(), automaticQueueModel.getOrder_money().intValue(), orderNumId);
} else if (segmentModel.getOperator().equals(SegmentType_Smart)) {
resultsModel = SmartSentUtils.sentTopUp(automaticQueueModel.getOrder_phone(), automaticQueueModel.getOrder_money().intValue(), orderNumId);
} else if (segmentModel.getOperator().equals(SegmentType_Seatel)) {
Paygo24Utils paygo = new Paygo24Utils();
String result = paygo.payment(automaticQueueModel.getOrder_phone(), automaticQueueModel.getSegment_id(), automaticQueueModel.getOrder_money());
resultsModel = new ResultsModel();
resultsModel.setTip(result);//描述
if (result.equals(Paygo24Utils.SUCCESS)) {
resultsModel.setSuccessful(true);
} else {
resultsModel.setSuccessful(false);
}
} else {
Paygo24Utils paygo = new Paygo24Utils();
String result = paygo.payment(automaticQueueModel.getOrder_phone(), automaticQueueModel.getSegment_id(), automaticQueueModel.getOrder_money());
resultsModel = new ResultsModel();
resultsModel.setTip(result);//描述
if (result.equals(Paygo24Utils.SUCCESS)) {
resultsModel.setSuccessful(true);
} else {
resultsModel.setSuccessful(false);
}
}
return resultsModel;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
//自动处理结果
@Override
public void automaticForTackResult(AutomaticQueueModel early, boolean success, String desc) {
......@@ -145,7 +211,7 @@ public class AutomaticCodeServiceImpl implements AutomaticCodeService {
orderLogModel.setLog_order_number(early.getOrder_num());
orderLogModel.setLog_type(4);
orderLogModel.setTime(newTime);
orderLogModel.setLog_content("充值失败,转入人工处理-"+desc);
orderLogModel.setLog_content("充值失败,转入人工处理-" + desc);
//添加订单操作日志
currencyMapper.AddTableForMysql(TransformationTools.CreatAddMysql(orderLogModel, NameValue.Table_order_log, "id", null));
......@@ -158,7 +224,7 @@ public class AutomaticCodeServiceImpl implements AutomaticCodeService {
}
//移除自动充值队列中
currencyMapper.DeleteDataById(NameValue.Table_automatic_queue,early.getId());
currencyMapper.DeleteDataById(NameValue.Table_automatic_queue, early.getId());
}
......
package com.library.test;
import net.sf.json.JSONObject;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Base64;
import java.util.Date;
public class test2 {
public static void main(String[] args) {
try {
String str2="v2VSgq7Q2Yqhp36s5TOzD13J5FMa:Go0wTNZdR53xNbxHwhneLF1p40Ma";
String text2 = Base64.getEncoder().encodeToString(str2.getBytes("UTF-8"));
System.out.println("Basic "+text2);
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
String timestamp = sdf.format(new Date());
System.out.println(timestamp);
} catch (Exception e) {
e.printStackTrace();
}
}
}
......@@ -17,33 +17,8 @@ import java.util.GregorianCalendar;
*/
public class ylmTest {
public static void main(String[] args) {
// String phone="13000000000";
// String password="123";
// String str=MD5Util.MD5Encode(password,null);
// String str2=MD5Util.MD5Encode( phone.substring(0,6)+str,null);
//
// System.out.println(str2);
//
//
System.out.println(System.currentTimeMillis());
System.out.println(new Timestamp(System.currentTimeMillis()));
//
// GregorianCalendar gcal = new GregorianCalendar();
// gcal.setTime(new Date());
// XMLGregorianCalendar xgcal = null;
// try {
// xgcal = DatatypeFactory.newInstance().newXMLGregorianCalendar(gcal);
// System.out.println(new Gson().toJson(xgcal));
// System.out.println(xgcal);
// } catch (DatatypeConfigurationException e) {
// e.printStackTrace();
// // Logger.getLogger(Paygo24Utils.class.getName()).log(Level.SEVERE,
// // null, e);
//
// }
//{"status":0,"code":"MSG_SUCCESS","message":"Success","txDetail":{"transDetailId":4551,"transDetailCode":"37363eef5895e3b0db52f3f79f611251","merchantId":null,"merchantCode":"ePayTest","merchantServiceId":null,"merchantServiceType":"TOPUP","transTime":1577946364313,"emServiceProvideId":null,"emServiceId":null,"emServiceCode":null,"status":1,"paymentType":null,"refId":"1121","transDescription":null,"transAmount":1.0,"currencyCode":"USD","transAmountConvert":null,"currencyExchangeRate":null,"acceptPaymentCurrencyCode":null,"discountType":"1","discountAmount":0.05,"commissionAmount":null,"transFee":0.0,"transTotalAmount":0.95,"transTotalAmountConvert":null,"customerPhoneNumber":"855883970777","customerName":null,"description":null,"paidTime":null,"paidTid":null,"paidEmoneyAccount":null,"paidFee":null,"paidChanel":null,"paidAmount":null,"paidCurrencyCode":null,"paidTip":null,"paidTotalAmount":null,"emCoporationId":null,"emCoporationMsisdn":null,"txPaymentTokenId":"S6a6oWb3RB2YAU48Wy6RbZwT01AUTh10xtNvcqOgMib32KB+KnUy68bVTm/G0GPKMRUHEM4OqAsYGxOKpkgANCDtX133IKCmw2+Y9OhUQkQOUq8HAD4EySiM0GZ/xkbJey9dPYmebRCouy5iwRl7acQbuMsHWsTCc7CEFUFNyyZzkGKjOXW8v/nq5tB7D/lxeXsspd9rHURVC4gc/NDU7MZPRxd4QPMMyRR2tZ7xHxIOXt6map1msd7Ce5uMD5mgFgNnyc4IVitNbAqGJuBeR3ixWYlaLF41LqJXgMwvGMhMbcAGlPzTMw97dREegXWCnpi4iLygk5tieyUZ5S34hg==","paymentQrCode":null},"pinCode":null,"billPaymentInfo":null}
}
......
......@@ -32,6 +32,9 @@
<listener>
<listener-class>com.library.util.SessionCounter</listener-class>
</listener>
<servlet>
<servlet-name>springmvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
......
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