Commit b5087268 authored by gzj34291's avatar gzj34291

金格

parent 61875cd6
package com.hand.kinggrid;
import java.util.Formatter;
/**
* <p>
* 字节 16进制字串转换工具类
* </p>
*
* @author hubin
* @Date 2016-01-20
*/
public class Byte2Hex {
/**
*
* 字节转换为 16 进制字符串
*
* @param b
* 字节
* @return
*/
public static String byte2Hex( byte b ) {
String hex = Integer.toHexString(b);
if ( hex.length() > 2 ) {
hex = hex.substring(hex.length() - 2);
}
while ( hex.length() < 2 ) {
hex = "0" + hex;
}
return hex;
}
/**
*
* 字节数组转换为 16 进制字符串
*
* @param bytes
* 字节数组
* @return
*/
public static String byte2Hex( byte[] bytes ) {
Formatter formatter = new Formatter();
for ( byte b : bytes ) {
formatter.format("%02x", b);
}
String hash = formatter.toString();
formatter.close();
return hash;
}
}
package com.hand.kinggrid;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
/**
* 合同相关测试(使用模板)接口
* @author Administrator
*
*/
public class ContractWithTemplate {
//public static final String SERVER_URL = "http://10.203.0.11:8989/tosignserver";
/**
* 信签服务器对接应用ID
*/
//public static final String APP_ID = "ac4a3bd1bf6f44fa86477ac251933259";
/**
* 信签服务器对接应用密钥
*/
// public static final String APP_SECURITY = "7lQ7GC1HSviWAFG6";
public static void main(String[] args) throws IOException {
//String contractid = "testte222211";
String contractid = UUID.randomUUID().toString().replaceAll("-", "");//合同编号,随机生成
JSONObject json = generateContract(contractid , null);
//System.out.println(json);
if(json.getInteger("code") == 1){//创建成功
downFiles(json.getJSONArray("doc_last_urls"), "d:/"+contractid,null,null,null);
json = signContract(contractid,null);
json = signContract2(contractid,null);
if(json.getInteger("code") == 1){//签署成功
downFiles(json.getJSONArray("record_saved_urls"), "d:/"+contractid,null,null,null);
System.out.println("record_saved_urls:"+json.getJSONArray("record_saved_urls"));
}else{
System.out.println(json);
}
}
}
/**
* 下载多个文件保存在文件夹
* @param urls
* @param savePath
* @throws IOException
*/
public static final void downFiles(JSONArray urls , String savePath,String server_url,String app_id,String app_security) throws IOException{
for (Object url : urls) {
downFile((String)url, savePath,server_url,app_id,app_security);
}
}
/**
* 下载文件保存
* @param url
* @param savePath
* @throws IOException
*/
public static final void downFile(String url , String savePath,String server_url,String app_id,String app_security) throws IOException{
HttpRequest request = MainRequest.createHttpRequest(url,server_url,app_id,app_security);
//HttpRequest request = new HttpRequest(url);
request.send();
int code = request.getResponseCode();
if(code==200){
FileOutputStream fos = null;
try{
String fileName = savePath;
if ((!savePath.endsWith("/")) && (!savePath.endsWith("\\"))) {
fileName = fileName + "/";
}
fileName = fileName + request.getDownFileName();
File file = new File(fileName);
fos = new FileOutputStream(file);
request.result(fos);
} finally {
if (fos != null)
fos.close();
}
}
else {
System.out.println("错误信息:" + request.resultToString());
}
}
/**
* 使用模板创建合同
* @throws IOException
*/
public static JSONObject generateContract(String contractid , String contract_tpl_code) throws IOException{
HttpRequest request = MainRequest.createHttpRequest("/api/contract/start",null,null,null);
//{"姓名":"李东长","cardname_ID":"360111198708080899","year":"2018","month":"01","day":"01"}
JSONObject docx_metadata = new JSONObject(true);
docx_metadata.put("INSURANCE_COMPANY", "信签售后");
docx_metadata.put("INSURANCE_MAN", "龚琪");
docx_metadata.put("PLATE_NUM", "京A88888");
docx_metadata.put("INSURANCE_YEAR", "2018");
docx_metadata.put("INSURANCE_MONTH", "05");
docx_metadata.put("INSURANCE_DAY", "21");
docx_metadata.put("INSURANCE_MONEY", "50000");
docx_metadata.put("SIGN_YEAR", "2018");
docx_metadata.put("SIGN_MONTH", "05");
docx_metadata.put("SIGN_DAY", "21");
//quest.addFile("attach_file", new File("d:/t1.pdf"));
//request.addFile("attach_file", new File("d:/t2.gif"));
//request.addFile("attach_file_2", new File("d:/test.docx"));
//request.addParam("contract_tlp_code",contract_tpl_code);
request.addParam("contract_tlp_code","nxs001");
request.addParam("doc_metadata",docx_metadata.toJSONString());
//设置合同ID
request.addParam("contract_id", contractid);
//设置合同名称参数
request.addParam("contract_name", "测试");
//设置业务编码参数
request.addParam("biz_id", UUID.randomUUID().toString().replaceAll("-", ""));
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//设置业务时间参数
request.addParam("biz_time", sdf.format(new Date()));
request.send();
return JSONObject.parseObject(request.resultToString());
}
/**
* 签署合同
* @throws IOException
*/
public static JSONObject signContract(String contractid , String signer_code ) throws IOException{
HttpRequest request = MainRequest.createHttpRequest("/api/contract/sign",null,null,null);
request.addParam("contract_id", contractid);
request.addParam("biz_id", UUID.randomUUID().toString().replaceAll("-", ""));
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//设置业务时间参数
request.addParam("biz_time", sdf.format(new Date()));
//设置签署人的编码
request.addParam("signer_code", signer_code);
//设置签署位置信息
//request.addParam("signatures", "[{ y:680,x:200,pageno:\"1\"}]");
request.send();
return JSONObject.parseObject(request.resultToString());
}
public static JSONObject signContract2(String contractid , String signer_code ) throws IOException{
HttpRequest request = MainRequest.createHttpRequest("/api/contract/sign",null,null,null);
request.addParam("contract_id", contractid);
request.addParam("biz_id", UUID.randomUUID().toString().replaceAll("-", ""));
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//设置业务时间参数
request.addParam("biz_time", sdf.format(new Date()));
//设置签署人的编码
request.addParam("signer_code", "xurong");
//设置签署位置信息
//request.addParam("signatures", "[{ y:680,x:200,pageno:\"1\"}]");
request.send();
return JSONObject.parseObject(request.resultToString());
}
}
package com.hand.kinggrid;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
public
class FileHolder {
private String filename;
private File file;
private InputStream is ;
public FileHolder(File file) {
this.filename = file.getName();
this.file = file;
}
public FileHolder(String filename , InputStream is) {
this.filename = filename;
this.is = is;
}
public InputStream getInputStream() throws FileNotFoundException{
if(is == null){
return new FileInputStream(file);
}
return is;
}
public String getFilename() {
return filename;
}
}
package com.hand.kinggrid;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
/**
* HTTP 简单封装
* @author Administrator
*
*/
public class HttpRequest {
/**
* https 域名校验
*/
private class TrustAnyHostnameVerifier implements HostnameVerifier {
public boolean verify(String hostname, SSLSession session) {
return true;
}
}
/**
* https 证书管理
*/
private class TrustAnyTrustManager implements X509TrustManager {
public X509Certificate[] getAcceptedIssuers() {
return null;
}
public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
}
public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
}
}
private static String CHARSET = "UTF-8";
private static final SSLSocketFactory sslSocketFactory = initSSLSocketFactory();
private static final TrustAnyHostnameVerifier trustAnyHostnameVerifier = new HttpRequest(null).new TrustAnyHostnameVerifier();
private static SSLSocketFactory initSSLSocketFactory() {
try {
TrustManager[] tm = {new HttpRequest(null).new TrustAnyTrustManager() };
SSLContext sslContext = SSLContext.getInstance("TLS"); // ("TLS", "SunJSSE");
sslContext.init(null, tm, new java.security.SecureRandom());
return sslContext.getSocketFactory();
}
catch (Exception e) {
throw new RuntimeException(e);
}
}
private static String end = "\r\n";
private static String PREFIX = "--";
public String url;
private String requestMethod = "POST";
private int readTimeout =30000;
protected Map<String,String> headers = new LinkedHashMap<String, String>();
protected Map<String , List<FileHolder>> fileMap = new LinkedHashMap<String, List<FileHolder>>();
protected Map<String,List<String>> params = new LinkedHashMap<String, List<String>>();
HttpURLConnection conn;
private int responseCode;
private String charset = CHARSET;
public HttpRequest(String url){
this.url = url;
}
/**
* 添加header信息
* @param key
* @param value
*/
public HttpRequest addHeader(String key , String value){
this.headers.put(key, value);
return this;
}
public HttpRequest addHeaders(Map<String,String> maps){
this.headers.putAll(maps);
return this;
}
public String getCharset() {
return charset;
}
public void setCharset(String charset) {
this.charset = charset;
}
/**
* 添加参数
* @param key
* @param value
*/
public HttpRequest addParam(String key , String value){
if(value==null || "".equals(value)){
return this;
}
List<String> files = params.get(key);
if(files == null){
files = new ArrayList<String>();
}
files.add(value);
this.params.put(key, files);
return this;
}
public HttpRequest addInputStream(String key , String filename , InputStream is){
List<FileHolder> files = fileMap.get(key);
if(files == null){
files = new ArrayList<FileHolder>();
}
files.add(new FileHolder(filename ,is ));
this.fileMap.put(key, files);
return this;
}
public HttpRequest addFile(String key , File file){
List<FileHolder> files = fileMap.get(key);
if(files == null){
files = new ArrayList<FileHolder>();
}
files.add(new FileHolder(file));
this.fileMap.put(key, files);
return this;
}
private void writeFile(OutputStream out, InputStream fis , String name , String filename) throws IOException{
out.write((PREFIX + boundary + end).getBytes(charset));
String contentDisposition = "Content-Disposition: form-data; name=\"" + name
+ "\"; filename=\"" + filename + "\""+end;
out.write(contentDisposition.getBytes(charset));
out.write(("Content-Type: application/octet-stream"+end).getBytes(charset));
out.write(end.getBytes(charset));
byte[] buffer = new byte[1024];
for (int n = -1; (n = fis.read(buffer)) != -1;) {
out.write(buffer, 0, n);
}
out.write(end.getBytes(charset));
}
private void writeFiles(OutputStream out) throws IOException{
Set<String> keySet = fileMap.keySet();
for (Iterator<String> it = keySet.iterator(); it.hasNext();) {
String name = it.next();
List<FileHolder> value = fileMap.get(name);
for (FileHolder fileHolder : value) {
InputStream fis = null;
try{
fis = fileHolder.getInputStream();
writeFile(out, fis, name, fileHolder.getFilename());
}finally{
if(fis!=null){
try{
fis.close();
}catch(Exception e){
}
}
}
}
}
out.write((PREFIX + boundary + PREFIX + end).getBytes(charset));
}
private void writeParams(OutputStream out) throws IOException{
Set<String> keySet = params.keySet();
StringBuffer sb = new StringBuffer();
int i = 0;
for (Iterator<String> it = keySet.iterator(); it.hasNext();) {
String name = it.next();
List<String> values = params.get(name);
for (String string : values) {
if(i>0){
sb.append("&");
}
sb.append(name).append("=").append(URLEncoder.encode(string , charset));
i++;
}
}
out.write(sb.toString().getBytes(charset));
}
private void writeParamsWithFile(OutputStream out) throws IOException{
Set<String> keySet = params.keySet();
StringBuffer sb = new StringBuffer();
for (Iterator<String> it = keySet.iterator(); it.hasNext();) {
String name = it.next();
List<String> values = params.get(name);
for (String string : values) {
sb.append(PREFIX).append(boundary).append(end);//分界符
sb.append("Content-Disposition: form-data; name=\"" + name + "\"" + end);
//sb.append("Content-Type: text/plain; charset=" + charset + end);
sb.append(end);
sb.append(string);
sb.append(end);
}
}
out.write(sb.toString().getBytes(charset));
}
private String boundary = "----TosignFormBoundary5TGBNHY67UJM";
public HttpRequest open() throws IOException{
URL _url = new URL(url);
conn = (HttpURLConnection)_url.openConnection();
if (conn instanceof HttpsURLConnection) {
((HttpsURLConnection)conn).setSSLSocketFactory(sslSocketFactory);
((HttpsURLConnection)conn).setHostnameVerifier(trustAnyHostnameVerifier);
}
conn.setRequestMethod(this.requestMethod);
conn.setDoInput(true); //允许输入流
conn.setDoOutput(true); //允许输出流
conn.setUseCaches(false); //不允许使用缓存
conn.setConnectTimeout(10000);
conn.setReadTimeout(readTimeout);
boolean hasUploadFile = !fileMap.isEmpty();
if(hasUploadFile){
conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
}else{
conn.setRequestProperty("Content-Type","application/x-www-form-urlencoded;charset=" + charset);
}
conn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.146 Safari/537.36");
if (headers != null && !headers.isEmpty())
for (Entry<String, String> entry : headers.entrySet())
conn.setRequestProperty(entry.getKey(), entry.getValue());
return this;
}
public int getReadTimeout() {
return readTimeout;
}
public void setReadTimeout(int readTimeout) {
this.readTimeout = readTimeout;
}
public HttpRequest write(byte[] data) throws IOException{
OutputStream out = conn.getOutputStream();
out.write(data);
return this;
}
public HttpRequest request() throws IOException{
boolean hasUploadFile = !fileMap.isEmpty();
OutputStream out = conn.getOutputStream();
if(hasUploadFile){
writeParamsWithFile(out);
writeFiles(out);
}else{
writeParams(out);
}
out.flush();
out.close();
responseCode = conn.getResponseCode();
return this;
}
/**
* 发送请求
* @return 返回状态码 requestCode
* @throws IOException
*/
public HttpRequest send() throws IOException{
open();
request();
return this;
}
public int getResponseCode() {
return responseCode;
}
/**
* 将响应结果以string返回
* @return
* @throws IOException
*/
public String resultToString() throws IOException{
String _charset = charset;
String contentType = conn.getContentType();
if(StrKit.notBlank(contentType)){
Pattern pattern = Pattern.compile("charset=\\S*");
Matcher matcher = pattern.matcher(conn.getContentType());
if (matcher.find()) {
_charset = matcher.group().replace("charset=", "");
}
}
ByteArrayOutputStream baos = new ByteArrayOutputStream();
result(baos);
return new String(baos.toByteArray() , _charset);
}
public String getDownFileName() throws IOException{
String contentDisposition = new String(conn.getHeaderField("content-disposition").getBytes("ISO8859-1") ,this.charset);
// 匹配文件名
Pattern pattern = Pattern.compile(".*filename=(.*)");
Matcher matcher = pattern.matcher(contentDisposition);
System.out.println(matcher.groupCount()+"1");
System.out.println(matcher.matches()+"2");
System.out.println(matcher.group(1)+"3");
String filename = matcher.group(1);
String s=filename.substring(1,filename.length()-1);
// System.out.println(s);
return filename.substring(1,filename.length()-1).replace("_1_saved.",".");
// return filename;
}
/**
* 将响应结果写入输出流,主要用于接收服务返回的文件
* @param os
* @throws IOException
*/
public void result(OutputStream os ) throws IOException{
InputStream inputStream = null;
try {
if(getResponseCode() >=400 && getResponseCode()!=404){
inputStream = conn.getErrorStream();
}else{
inputStream = conn.getInputStream();
}
byte[] buffer = new byte[2048];
for (int n = -1; (n = inputStream.read(buffer)) != -1;) {
os.write(buffer, 0, n);
os.flush();
}
}
finally {
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
}
}
conn.disconnect();
}
}
public HttpURLConnection getConn() {
return conn;
}
public String getRequestMethod() {
return requestMethod;
}
public void setRequestMethod(String requestMethod) {
this.requestMethod = requestMethod;
}
}
package com.hand.kinggrid;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.TreeMap;
import java.util.logging.Logger;
public class MD5 {
private static final Logger logger = Logger.getLogger("MD5");
/**
* @Description 字符串加密为MD5 中文加密一致通用,必须转码处理: plainText.getBytes("UTF-8")
* @param plainText
* 需要加密的字符串
* @return
*/
public static String toMD5(String plainText) {
StringBuffer rlt = new StringBuffer();
try {
rlt.append(md5String(plainText.getBytes("UTF-8")));
} catch (UnsupportedEncodingException e) {
logger.severe(" CipherHelper toMD5 exception.");
e.printStackTrace();
}
return rlt.toString();
}
/**
* MD5 参数签名生成算法
*
* @param HashMap<String,String>
* params 请求参数集,所有参数必须已转换为字符串类型
* @param String
* secret 签名密钥
* @return 签名
* @throws IOException
*/
public static String getSignature(HashMap<String, String> params, String secret) {
Map<String, String> sortedParams = new TreeMap<String, String>(params);
Set<Entry<String, String>> entrys = sortedParams.entrySet();
StringBuilder basestring = new StringBuilder();
for (Entry<String, String> param : entrys) {
basestring.append(param.getKey()).append("=").append(param.getValue());
}
return getSignature(basestring.toString(), secret);
}
/**
* MD5 参数签名生成算法
*
* @param String
* sigstr 签名字符串
* @param String
* secret 签名密钥
* @return 签名
* @throws IOException
*/
public static String getSignature(String sigstr, String secret) {
StringBuilder basestring = new StringBuilder(sigstr);
basestring.append("#");
basestring.append(toMD5(secret));
return toMD5(basestring.toString());
}
public static byte[] md5Raw(byte[] data) {
byte[] md5buf = null;
try {
MessageDigest md5 = MessageDigest.getInstance("MD5");
md5buf = md5.digest(data);
} catch (Exception e) {
md5buf = null;
logger.severe("md5Raw error.");
e.printStackTrace();
}
return md5buf;
}
public static String md5String(byte[] data) {
String md5Str = "";
try {
MessageDigest md5 = MessageDigest.getInstance("MD5");
byte[] buf = md5.digest(data);
for (int i = 0; i < buf.length; i++) {
md5Str += Byte2Hex.byte2Hex(buf[i]);
}
} catch (Exception e) {
md5Str = null;
logger.severe("md5String error.");
e.printStackTrace();
}
return md5Str;
}
}
\ No newline at end of file
package com.hand.kinggrid;
public class MainRequest {
/**
* 信签服务器地址
*/
//public static final String SERVER_URL = "http://171.34.78.70:8081:8081/tosignserver";
//public static final String SERVER_URL = "http://10.203.0.11:8989/tosignserver";
// public static final String SERVER_URL = "http://171.34.78.70:8081/tosignpub";
/**
* 信签服务器对接应用ID
*/
//public static final String APP_ID = "king";
// public static final String APP_ID = "ac4a3bd1bf6f44fa86477ac251933259";
//public static final String APP_ID = "f12a2c19e72348998b159df903b9b379";
/**
* 信签服务器对接应用密钥
*/
//public static final String APP_SECURITY = "e3f55030d473095d";
// public static final String APP_SECURITY = "7lQ7GC1HSviWAFG6";
//public static final String APP_SECURITY = "SK60MXsN7dzv1iIM";
//public static final String APP_ID = "f12a2c19e72348998b159df903b9b379";
/**
* 测试签署用户编码
*/
//public static final String SIGNER_CODE= "hlzlUser";
//public static final String SIGNER_CODE= "lidongzhang";
/**
* 模板创建合同使用的模板编码
*/
//public static final String CONTRACT_TPL_CODE= "testTemplate";
public static void main(String[] args) {
}
/**
* 生成信签请求操作对象
* @param url
* @return
*/
public static HttpRequest createHttpRequest(String url,String server_url,String app_id,String app_security){
String requestUrl = url;
if(!url.toUpperCase().startsWith("HTTP")){
if(server_url.endsWith("/")){
requestUrl = server_url.substring(0, server_url.length()-1)+url;
}else{
requestUrl = server_url+url;
}
}
HttpRequest httpRequest = new HttpRequest(requestUrl);
/**
* 如果是云服务,需要添加应用id到header
* 如果是私有云,可以不用设置
*/
httpRequest.addHeader("app_id", app_id);
String time = System.currentTimeMillis()+"";
httpRequest.addHeader("time", time);
httpRequest.addHeader("sign", MD5.toMD5(app_id+"."+time+'.'+app_security));
return httpRequest;
}
}
package com.hand.kinggrid;
public class StrKit {
public static boolean notBlank(String str) {
return !isBlank(str);
}
public static boolean isBlank(String str) {
if (str == null) {
return true;
}
int len = str.length();
if (len == 0) {
return true;
}
for (int i = 0; i < len; i++) {
switch (str.charAt(i)) {
case ' ':
case '\t':
case '\n':
case '\r':
// case '\b':
// case '\f':
break;
default:
return false;
}
}
return true;
}
}
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