You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

340 lines
13 KiB
Java

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

package com.weaver.seconddev.sxjg.util;
import com.alibaba.fastjson.JSONObject;
import com.weaver.ebuilder.common.exception.BusinessException;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.configuration.PropertiesConfiguration;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.OAEPParameterSpec;
import javax.crypto.spec.PSource;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.security.*;
import java.security.spec.MGF1ParameterSpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.HashMap;
import java.util.Map;
public class NccApiUtil2 {
private static final Logger log = LoggerFactory.getLogger(NccApiUtil2.class);
public String getBaseUrl() {
return baseUrl;
}
public void setBaseUrl(String baseUrl) {
this.baseUrl = baseUrl;
}
private String baseUrl;
// 访问的nccloud系统的账套编码开发环境使用develop生产环境需要使用用root账号登录在“系统管理”节点查看账套编码由陕西建工HR系统提供
private String biz_center;
public String getClient_id() {
return client_id;
}
public void setClient_id(String client_id) {
this.client_id = client_id;
}
//陕煤HR系统在陕西建工HR系统中应用注册当中的app_id
private String client_id;
//陕煤HR系统在陕西建工HR系统中应用注册当中的app_secret由陕西建工HR系统提供
private String client_secret;
//陕西建工HR系统中应用注册当中的(公钥)pubKey由陕西建工HR系统提供
private String pubKey;
private String signature;
public void init() {
PropertiesConfiguration p = null;
try {
p = new PropertiesConfiguration();
p.setEncoding("utf-8");
p.setFileName("config/nccconfig.properties");
p.load();
this.baseUrl = p.getString("sxjgncc.url");
this.biz_center = p.getString("sxjgncc.biz_center");
this.client_id = p.getString("sxjgncc.client_id");
this.client_secret = p.getString("sxjgncc.client_secret");
this.pubKey = p.getString("sxjgncc.public_key");
}catch (ConfigurationException e) {
throw new BusinessException("获取sxjg.properties配置文件失败", e);
}
}
/**
* 获取设置的ncc用户token
* @return@
* @throws Exception
*/
public String getToken() throws Exception {
Map<String, String> paramMap = new HashMap();
//获取token方式固定为client_credentials
paramMap.put("grant_type", "client_credentials");
//陕煤HR系统在陕西建工HR系统中应用注册当中的app_id由陕西建工HR系统提供
paramMap.put("client_id", this.client_id);
//加密陕煤HR系统在陕西建工HR系统中应用注册当中的(公钥)pubKey和app_secret由陕西建工HR系统提供
String encode = URLEncoder.encode(pubEncrypt(this.pubKey, this.client_secret), "UTF-8");//需要写入报文头中
paramMap.put("client_secret", encode);
// 账套编码开发环境使用develop生产环境需要使用用root账号登录在“系统管理”节点查看账套编码由陕西建工HR系统提供
paramMap.put("biz_center", this.biz_center);
//请求加签其算法getSHA256(client_id + client_secret + pubKey)
String sign = getSHA256(this.client_id + this.client_secret + this.pubKey, this.pubKey);
paramMap.put("signature", sign);//需要写入报文头中
this.setSignature(sign);
//查询token的url
String url = this.baseUrl + "nccloud/opm/accesstoken";
String mediaType = "application/x-www-form-urlencoded";
String token = this.doPost(url, paramMap, mediaType, (Map)null, "");
JSONObject rs = JSONObject.parseObject(token);
if(rs.getBoolean("success")) {
JSONObject jsonObject = rs.getJSONObject("data");
String token1 = jsonObject.getString("access_token");
return token1;
}else {
log.error("howec::::::::::::111:"+token);
throw new Exception("获取toaken失败");
}
}
public String doJsonPost(String url, String accessToken, String json) {
log.error("NCC接口"+url+",推送报文:>>>>>>>>>>>>>>>>>>>>>>"+json);
CloseableHttpClient client = HttpClients.createDefault();
HttpPost post = new HttpPost(url);
post.setHeader("Content-Type", "application/json;charset=utf-8");
post.setHeader("access_token", accessToken);
post.setHeader("repeat_check","Y");
post.setHeader("ucg_flag","Y");
post.setHeader("signature",this.getSignature());
post.setHeader("client_id",this.getClient_id());
String result="";
try {
StringEntity s = new StringEntity(json,"UTF-8");
s.setContentEncoding("utf-8");
s.setContentType("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;
while ((line = reader.readLine()) != null)
strber.append(line + "\n");
inStream.close();
result = strber.toString();
log.error("NCC接口"+url+",返回值:>>>>>>>>>>>>>>>>>>>>>>"+result);
} catch (Exception e) {
e.printStackTrace();
log.error("NCC接口"+url+",返回值:>>>>>>>>>>>1>>>>>>>>>>>"+e.getMessage());
}
return result;
}
public static String pubEncrypt(String pubKey, String src) throws Exception {
String target = null;
ByteArrayOutputStream out = null;
try {
Key key = getPublicKey(pubKey);
Cipher cipher = Cipher.getInstance("RSA/ECB/OAEPWithSHA-256AndMGF1Padding");
cipher.init(1, key, new OAEPParameterSpec("SHA-256", "MGF1", new MGF1ParameterSpec("SHA-256"), PSource.PSpecified.DEFAULT));
byte[] data = src.getBytes();
int inputLen = data.length;
out = new ByteArrayOutputStream();
int offSet = 0;
for(int i = 0; inputLen - offSet > 0; offSet = i * 117) {
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;
}
target = (new Base64()).encodeToString(out.toByteArray());
} catch (NoSuchPaddingException | InvalidKeyException | IllegalBlockSizeException | BadPaddingException | NoSuchAlgorithmException var14) {
throw new Exception("加密失败", var14);
} finally {
if (out != null) {
out.close();
}
}
return target;
}
public static Key getPublicKey(String pubKey) throws Exception {
PublicKey key = null;
try {
byte[] keyBytes = (new Base64()).decode(pubKey);;
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes);
key = keyFactory.generatePublic(x509KeySpec);
return key;
} catch (Exception var5) {
throw new Exception("无效的密钥 ", var5);
}
}
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 Base64()).encodeToString(salt);
return getSHA256(str + salt_value.replaceAll("\r|\n", ""));
}
private static String getSHA256(String str) throws Exception {
String encodestr = "";
MessageDigest messageDigest = MessageDigest.getInstance("SHA-256");
messageDigest.update(str.getBytes("UTF-8"));
encodestr = byte2Hex(messageDigest.digest());
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] & 255);
if (temp.length() == 1) {
stringBuffer.append("0");
}
stringBuffer.append(temp);
}
return stringBuffer.toString();
}
/**
* 发送post请求
*
* @param baseUrl
* @param paramMap
* @param mediaType
* @param headers
* @param json
* @return
*/
private static String doPost(String baseUrl, Map<String, String> paramMap, String mediaType, Map<String, String> headers, String json) {
HttpURLConnection urlConnection = null;
InputStream in = null;
OutputStream out = null;
BufferedReader bufferedReader = null;
String result = null;
try {
StringBuffer sb = new StringBuffer();
sb.append(baseUrl);
if (paramMap != null) {
sb.append("?");
for (Map.Entry<String, String> entry : paramMap.entrySet()) {
String key = entry.getKey();
String value = entry.getValue();
sb.append(key + "=" + value).append("&");
}
baseUrl = sb.toString().substring(0, sb.toString().length() - 1);
}
URL urlObj = new URL(baseUrl);
urlConnection = (HttpURLConnection) urlObj.openConnection();
urlConnection.setConnectTimeout(50000);
urlConnection.setRequestMethod("POST");
urlConnection.setDoOutput(true);
urlConnection.setDoInput(true);
urlConnection.setUseCaches(false);
urlConnection.addRequestProperty("content-type", mediaType);
if (headers != null) {
for (String key : headers.keySet()) {
urlConnection.addRequestProperty(key, headers.get(key));
}
}
out = urlConnection.getOutputStream();
out.write(json.getBytes("utf-8"));
out.flush();
int resCode = urlConnection.getResponseCode();
if (resCode == HttpURLConnection.HTTP_OK || resCode == HttpURLConnection.HTTP_CREATED || resCode == HttpURLConnection.HTTP_ACCEPTED) {
in = urlConnection.getInputStream();
} else {
in = urlConnection.getErrorStream();
}
bufferedReader = new BufferedReader(new InputStreamReader(in, "utf-8"));
StringBuffer temp = new StringBuffer();
String line = bufferedReader.readLine();
while (line != null) {
temp.append(line).append("\r\n");
line = bufferedReader.readLine();
}
String ecod = urlConnection.getContentEncoding();
if (ecod == null) {
ecod = Charset.forName("utf-8").name();
}
result = new String(temp.toString().getBytes("utf-8"), ecod);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (null != bufferedReader) {
try {
bufferedReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (null != out) {
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (null != in) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
urlConnection.disconnect();
}
return result;
}
public String getSignature() {
return signature;
}
public void setSignature(String signature) {
this.signature = signature;
}
}