406 lines
14 KiB
Java
406 lines
14 KiB
Java
package nccloud.openapi;
|
||
|
||
|
||
import com.alibaba.fastjson.JSONObject;
|
||
import nc.ws.opm.pub.utils.security.SecurityUtil;
|
||
import nccloud.openapi.BaseOpenApiTest.HttpClientWapper.Response;
|
||
import org.apache.commons.httpclient.Header;
|
||
import org.apache.commons.httpclient.HttpClient;
|
||
import org.apache.commons.httpclient.NameValuePair;
|
||
import org.apache.commons.httpclient.methods.GetMethod;
|
||
import org.apache.commons.httpclient.methods.PostMethod;
|
||
import org.apache.commons.httpclient.methods.StringRequestEntity;
|
||
import org.apache.commons.httpclient.util.EncodingUtil;
|
||
import org.apache.commons.lang3.StringUtils;
|
||
import org.springframework.core.io.ClassPathResource;
|
||
import sun.misc.BASE64Decoder;
|
||
import sun.misc.BASE64Encoder;
|
||
|
||
import javax.crypto.Cipher;
|
||
import java.io.*;
|
||
import java.net.URLEncoder;
|
||
import java.nio.charset.StandardCharsets;
|
||
import java.security.*;
|
||
import java.security.spec.X509EncodedKeySpec;
|
||
import java.util.*;
|
||
import java.util.Map.Entry;
|
||
|
||
/**
|
||
* @description: 审批流程接口测试
|
||
* @author:guoxqc@yonyou.com
|
||
* @date:2020年10月23日
|
||
*/
|
||
public class BaseOpenApiTest {
|
||
// public static final String BASE_URL_DEV="http://192.168.82.5:9999";
|
||
public static final String BASE_URL_DEV = "http://127.0.0.1:8088";
|
||
// public static final String BASE_URL_DEV = "http://192.168.82.104:7788";
|
||
// public static final String BASE_URL_DEV="http://192.168.82.1:9081";
|
||
// public static final String BASE_URL_DEV="http://172.23.17.146:8001";
|
||
/**
|
||
* APP ID
|
||
*/
|
||
public static final String CLIENT_ID;
|
||
/**
|
||
* APP Secret
|
||
*/
|
||
public static final String CLIENT_SECRET;
|
||
/**
|
||
* 公钥
|
||
*/
|
||
public static final String PUBLIC_KEY;
|
||
/**
|
||
* 账套编码
|
||
*/
|
||
public static final String BIZ_CENTER;
|
||
/**
|
||
* 用户编码
|
||
*/
|
||
public static final String USER_CODE;
|
||
|
||
static {
|
||
ResourceBundle config = ResourceBundle.getBundle("nccloud.openapi.config");
|
||
CLIENT_ID = config.getString("client_id");
|
||
CLIENT_SECRET = config.getString("client_secret");
|
||
PUBLIC_KEY = config.getString("pub_key");
|
||
BIZ_CENTER = config.getString("biz_center");
|
||
USER_CODE = config.getString("user_code");
|
||
}
|
||
|
||
public HttpClientWapper client = new HttpClientWapper();
|
||
|
||
/**
|
||
* @param url
|
||
* @param param
|
||
* @return
|
||
* @throws Exception
|
||
*/
|
||
public String requestOpenApi(String url, Map<String, Object> param) throws Exception {
|
||
return requestOpenApi(url, new JSONObject(param));
|
||
}
|
||
|
||
/**
|
||
* @param url
|
||
* @param param
|
||
* @return
|
||
* @throws Exception
|
||
*/
|
||
public String requestOpenApi(String url, JSONObject param) throws Exception {
|
||
return requestOpenApi(url, param.toJSONString());
|
||
}
|
||
|
||
/**
|
||
* @param url
|
||
* @param fileName
|
||
* @return
|
||
* @throws Exception
|
||
*/
|
||
public String requestOpenApiByJSON(String url, String fileName) throws Exception {
|
||
ClassPathResource classPathResorce = new ClassPathResource(fileName, this.getClass());
|
||
StringBuffer data = new StringBuffer();
|
||
try {
|
||
InputStream in = classPathResorce.getInputStream();
|
||
BufferedReader reader = new BufferedReader(new InputStreamReader(in, "utf-8"));
|
||
String line = reader.readLine();
|
||
while (StringUtils.isNotEmpty(line)) {
|
||
data.append(line);
|
||
line = reader.readLine();
|
||
}
|
||
} catch (IOException e1) {
|
||
e1.printStackTrace();
|
||
}
|
||
return requestOpenApi(url, data.toString());
|
||
}
|
||
|
||
public String requestOpenApi(String url, String param) throws Exception {
|
||
String accessToken = this.getAccessTokenByClient();
|
||
System.out.println(param.replace(" ", ""));
|
||
String sign = digest(CLIENT_ID + PUBLIC_KEY);
|
||
List<Header> headers = new ArrayList<Header>();
|
||
headers.add(new Header("Content-Type", "application/json;charset=UTF-8"));
|
||
headers.add(new Header("signature", sign));
|
||
headers.add(new Header("ucg_flag", "y"));
|
||
headers.add(new Header("access_token", accessToken));
|
||
headers.add(new Header("client_id", CLIENT_ID));
|
||
Response response;
|
||
try {
|
||
response = client.post(BASE_URL_DEV + url, headers.toArray(new Header[headers.size()]), null, param);
|
||
// System.out.println(response.getData());
|
||
return response.getData();
|
||
} catch (Exception e) {
|
||
System.out.println(e.getMessage());
|
||
e.printStackTrace();
|
||
return e.getMessage();
|
||
}
|
||
}
|
||
|
||
/**
|
||
* @param seed 种子,用于生成公钥
|
||
* @param src 明文
|
||
* @return
|
||
* @throws Exception
|
||
* @description RSA加密
|
||
*/
|
||
public String pubEncrypt(String seed, String src) throws Exception {
|
||
String target = null;
|
||
ByteArrayOutputStream out = null;
|
||
try {
|
||
Key key = genPublicKey(PUBLIC_KEY);
|
||
Cipher cipher = Cipher.getInstance("RSA");
|
||
cipher.init(1, key);
|
||
byte[] data = src.getBytes();
|
||
int inputLen = data.length;
|
||
out = new ByteArrayOutputStream();
|
||
int offSet = 0;
|
||
int i = 0;
|
||
while (inputLen - offSet > 0) {
|
||
byte[] cache;
|
||
;
|
||
if (inputLen - offSet > 117) {
|
||
cache = cipher.doFinal(data, offSet, 117);
|
||
} else {
|
||
cache = cipher.doFinal(data, offSet, inputLen - offSet);
|
||
}
|
||
out.write(cache, 0, cache.length);
|
||
i++;
|
||
offSet = i * 117;
|
||
}
|
||
target = new BASE64Encoder().encodeBuffer(out.toByteArray());
|
||
} catch (Exception e) {
|
||
throw new Exception("加密失败" + e.getMessage());
|
||
} finally {
|
||
if (out != null) {
|
||
out.close();
|
||
}
|
||
}
|
||
return target;
|
||
}
|
||
|
||
/**
|
||
* @param str
|
||
* @return
|
||
* @description 信息摘要
|
||
*/
|
||
public static String digest(String str) {
|
||
String encodestr = "";
|
||
try {
|
||
MessageDigest messageDigest = MessageDigest.getInstance("SHA-256");
|
||
messageDigest.update(str.getBytes(StandardCharsets.UTF_8));
|
||
encodestr = byte2Hex(messageDigest.digest());
|
||
} catch (NoSuchAlgorithmException e) {
|
||
throw new RuntimeException(e);
|
||
}
|
||
return encodestr;
|
||
}
|
||
|
||
private static String byte2Hex(byte[] bytes) {
|
||
StringBuffer stringBuffer = new StringBuffer();
|
||
String temp = null;
|
||
for (int i = 0; i < bytes.length; i++) {
|
||
temp = Integer.toHexString(bytes[i] & 0xFF);
|
||
if (temp.length() == 1) {
|
||
stringBuffer.append("0");
|
||
}
|
||
stringBuffer.append(temp);
|
||
}
|
||
return stringBuffer.toString();
|
||
}
|
||
|
||
/**
|
||
* @param PUBLIC_KEY
|
||
* @return
|
||
* @throws Exception
|
||
* @description 根据种子生成密钥对
|
||
*/
|
||
public static Key genPublicKey(String seed) throws Exception {
|
||
Key key = null;
|
||
try {
|
||
byte[] keyBytes = new BASE64Decoder().decodeBuffer(seed);
|
||
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
|
||
X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes);
|
||
key = keyFactory.generatePublic(x509KeySpec);
|
||
} catch (Exception e) {
|
||
throw new Exception("无效的密钥 " + e.getMessage());
|
||
}
|
||
return key;
|
||
}
|
||
|
||
/**
|
||
* Http请求包装类
|
||
*
|
||
* @author guoxiangqiao
|
||
* @date 2019年12月11日
|
||
*/
|
||
public class HttpClientWapper {
|
||
public static final int HTTP_STATUS_SUCCESS = 200;
|
||
|
||
/**
|
||
* post请求
|
||
*
|
||
* @param url
|
||
* @param headers
|
||
* @param requestBody
|
||
* @return
|
||
* @throws Exception
|
||
*/
|
||
public Response post(String url, Header[] headers, NameValuePair[] requestBody, String requestEntityStr) throws Exception {
|
||
HttpClient client = new HttpClient();
|
||
PostMethod postMethod = new PostMethod(url);
|
||
if (headers != null) {
|
||
for (Header header : headers) {
|
||
postMethod.setRequestHeader(header);
|
||
}
|
||
}
|
||
if (requestBody != null) {
|
||
postMethod.setRequestBody(requestBody);
|
||
}
|
||
if (StringUtils.isNotEmpty(requestEntityStr)) {
|
||
StringRequestEntity requestEntity = new StringRequestEntity(requestEntityStr, null, "utf-8");
|
||
postMethod.setRequestEntity(requestEntity);
|
||
}
|
||
int httpStatus = client.executeMethod(postMethod);
|
||
String result = this.getResponseBodyAsString(postMethod);
|
||
return new Response(httpStatus, result);
|
||
}
|
||
|
||
public String getResponseBodyAsString(PostMethod postMethod) throws IOException {
|
||
byte[] rawdata = null;
|
||
rawdata = postMethod.getResponseBody();
|
||
return rawdata != null ? EncodingUtil.getString(rawdata, "utf-8") : null;
|
||
}
|
||
|
||
/**
|
||
* @param params
|
||
* @return
|
||
* @description Map转URL参数
|
||
* @author guoxqc@yonyou.com
|
||
* @date 2020年10月22日
|
||
*/
|
||
public String getURLParam(Map<String, Object> params) {
|
||
StringBuffer paramStr = new StringBuffer();
|
||
if (!params.isEmpty()) {
|
||
for (Entry<String, Object> kv : params.entrySet()) {
|
||
paramStr.append(kv.getKey());
|
||
paramStr.append("=");
|
||
paramStr.append(kv.getValue());
|
||
paramStr.append("&");
|
||
}
|
||
paramStr.deleteCharAt(paramStr.length() - 1);
|
||
}
|
||
return paramStr.toString();
|
||
}
|
||
|
||
/**
|
||
* get请求
|
||
*
|
||
* @param url
|
||
* @param headers
|
||
* @param params
|
||
* @return
|
||
* @throws Exception
|
||
*/
|
||
public Response get(String url, Header[] headers, NameValuePair[] params) throws Exception {
|
||
HttpClient client = new HttpClient();
|
||
GetMethod getMethod = new GetMethod(url);
|
||
if (params != null) {
|
||
getMethod.setQueryString(params);
|
||
}
|
||
if (headers != null) {
|
||
for (Header header : headers) {
|
||
getMethod.setRequestHeader(header);
|
||
}
|
||
}
|
||
int httpStatus = client.executeMethod(getMethod);
|
||
String result = getMethod.getResponseBodyAsString();
|
||
return new Response(httpStatus, result);
|
||
}
|
||
|
||
/**
|
||
* 获取url查询参数
|
||
*
|
||
* @param params
|
||
* @return
|
||
*/
|
||
public String getQueryString(NameValuePair[] params) {
|
||
GetMethod getMethod = new GetMethod();
|
||
getMethod.setQueryString(params);
|
||
return getMethod.getQueryString();
|
||
}
|
||
|
||
class Response {
|
||
private int httpStatus;
|
||
private String data;
|
||
|
||
public int getHttpStatus() {
|
||
return httpStatus;
|
||
}
|
||
|
||
public void setHttpStatus(int httpStatus) {
|
||
this.httpStatus = httpStatus;
|
||
}
|
||
|
||
public String getData() {
|
||
return data;
|
||
}
|
||
|
||
public void setData(String data) {
|
||
this.data = data;
|
||
}
|
||
|
||
public Response(int httpStatus, String data) {
|
||
super();
|
||
this.httpStatus = httpStatus;
|
||
this.data = data;
|
||
}
|
||
|
||
public Response() {
|
||
super();
|
||
}
|
||
}
|
||
}
|
||
|
||
public static String getSHA256(String str, String key) throws Exception {
|
||
byte[] salt = new byte[16];
|
||
SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
|
||
random.setSeed(key.getBytes());
|
||
random.nextBytes(salt);
|
||
String salt_value = new BASE64Encoder().encodeBuffer(salt);
|
||
return digest(str + salt_value.replaceAll("\r|\n", ""));
|
||
}
|
||
|
||
/**
|
||
* @return
|
||
* @throws Exception
|
||
* @description 获取AccessToken
|
||
*/
|
||
@SuppressWarnings("static-access")
|
||
public String getAccessTokenByClient() throws Exception {
|
||
String url = BASE_URL_DEV + "/nccloud/opm/accesstoken";
|
||
List<Header> headers = new ArrayList<Header>();
|
||
headers.add(new Header("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8"));
|
||
// 获取信息摘要
|
||
String signature = getSHA256(CLIENT_ID + CLIENT_SECRET + PUBLIC_KEY, PUBLIC_KEY);
|
||
// 使用PUBLIC_KEY生成公钥,对CLIENT_SECRET加密
|
||
SecurityUtil securityUtil = new SecurityUtil();
|
||
String CLIENT_SECRETEn = URLEncoder.encode(securityUtil.pubEncrypt(PUBLIC_KEY, CLIENT_SECRET), "utf-8");
|
||
Map<String, Object> params = new HashMap<String, Object>();
|
||
params.put("client_id", CLIENT_ID);
|
||
params.put("userCode", USER_CODE);
|
||
params.put("grant_type", "client_credentials");
|
||
params.put("biz_center", BIZ_CENTER);
|
||
params.put("signature", signature);
|
||
params.put("client_secret", CLIENT_SECRETEn);
|
||
try {
|
||
Response response = client.post(url, headers.toArray(new Header[headers.size()]), null, client.getURLParam(params));
|
||
System.out.println(response.getData());
|
||
JSONObject result = JSONObject.parseObject(response.getData());
|
||
boolean success = result.getBoolean("success");
|
||
if (success) {
|
||
return result.getJSONObject("data").getString("access_token");
|
||
}
|
||
} catch (Exception e) {
|
||
System.out.println(e.getMessage());
|
||
e.printStackTrace();
|
||
}
|
||
return null;
|
||
}
|
||
} |