1.获取redis中的key 值
String token = valueOperations.get(mobWxLoginVo.getKey());
2.token转换为json
JsonObject json = new Gson().fromJson(token, JsonObject.class);
3.取值
json.get("openid").getAsString()
CloseableHttpClient client = HttpClients.createDefault();
CloseableHttpResponse res = null;
JsonObject json = null;
QiandaoOutVo qov = null;
try {
// ObjectMapper objectMapper = new ObjectMapper();
// ObjectNode rootNode = objectMapper.createObjectNode();
// Map<String, Object> rootNode = new HashMap<>();
Map<String, Object> rootNode = Maps.newLinkedHashMap();
Map<String, String> map = yibaoMapper.queryInfo(1);
HttpPost httpPost = new HttpPost(map.get("ybjkdz") + "9001");
rootNode.put("infno", "9001");
String date = DateUtils.date2Str(DateUtils.yyyymmddhhmmss.get());
Random r = new Random();
int i = r.nextInt(9999);
String format = String.format("%04d", i);
String his_yybh = map.get("his_yybh") + date + format;
rootNode.put("msgid", his_yybh);//"H43122200572202302070804091990"
rootNode.put("mdtrtarea_admvs", "431222");
rootNode.put("insuplc_admdvs", "431222");
rootNode.put("recer_sys_code", "MBS_LOCAL");
rootNode.put("dev_no", "1");
rootNode.put("dev_safe_info", "1");
rootNode.put("cainfo", "3333");
rootNode.put("signtype", "SM2");
rootNode.put("infver", "V1.0");
rootNode.put("opter_type", "1");
rootNode.put("opter", "163");
rootNode.put("opter_name", "许诚");
rootNode.put("inf_time", DateUtils.date2Str(DateUtils.datetimeFormat.get()));//"2023-02-07 08:04:09"
rootNode.put("fixmedins_code", map.get("his_yybh"));//"H43122200572"
rootNode.put("fixmedins_name", "沅陵友好医院");
rootNode.put("sign_no", "");
Map<String, String> signIn = new HashMap<>();
signIn.put("opter_no", "163");
signIn.put("mac", "8C:89:A5:25:0D:35");
signIn.put("ip", "192.168.2.3");
Map<String, Map<String, String>> input = new HashMap<>();
input.put("signIn", signIn);
rootNode.put("input", input);
String timeMillis = String.valueOf(System.currentTimeMillis());
httpPost.setHeader("_api_name", "9001");
httpPost.setHeader("_api_version", "1.0.0");
httpPost.setHeader("_api_timestamp", timeMillis);//"1675728249000"
httpPost.setHeader("_api_access_key", map.get("ybgy"));//Jf8dln90JY4cl67y06HyWiDcB0RLpexuhHdmQi
String signCalc = signCalc("9001", "1.0.0", map.get("ybgy"), map.get("ybsy"), timeMillis);
httpPost.setHeader("_api_signature", signCalc);//JrpkTxRw0DNA/qzP2ysoRYPOB9A=//lflzbRlVmA8mxGcoga2WSmmazxw=
// ByteArrayOutputStream bos = new ByteArrayOutputStream();
// objectMapper.writeValue(bos, rootNode);
StringEntity reqEntity = new StringEntity(JSON.toJSONString(rootNode), ContentType.create("application/json", "utf-8"));
// httpPost.setEntity(new StringEntity(bos.toString("UTF-8"), ContentType.create("application/json", "utf-8")));
// ...
httpPost.setEntity(reqEntity);
res = client.execute(httpPost);
String responseContent = null; // 响应内容
HttpEntity entity = res.getEntity();
responseContent = EntityUtils.toString(entity, "UTF-8");
JsonElement jsonElement = new JsonParser().parse(responseContent);
json = jsonElement.getAsJsonObject();
GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES);
Gson gson = gsonBuilder.create();
//{"output":{"signinoutb":{"sign_no":"206501861","sign_time":"2023-03-18 11:11:25"}},"infcode":0,"warn_msg":null,"cainfo":null,"err_msg":"success","refmsg_time":"20230318111035671","signtype":null,"respond_time":"20230318111035698","inf_refmsgid":"430000202303181110350008012807"}
if (json.get("infcode").getAsInt() == 0) {
qov = gson.fromJson(jsonElement, QiandaoOutVo.class);
// gson.fromJson(responseContent, new TypeToken<Map<String, String>>(){}.getType());
// Set<Map.Entry<String, JsonElement>> entries = json.entrySet();
// for (Map.Entry<String, JsonElement> map: entries){
// QiandaoOutVo t = new Gson().fromJson(map.getValue(), QiandaoOutVo.class);
// }
// ParserConfig.getGlobalInstance().propertyNamingStrategy = PropertyNamingStrategy.SnakeCase;
// qov = JSON.parseObject(responseContent, QiandaoOutVo.class);
} else {
QiandaoErrorVo qiandaoErrorVo = gson.fromJson(jsonElement, QiandaoErrorVo.class);
return Result.ERROR(null, qiandaoErrorVo);
}
// json = new JsonParser().parse(responseContent).getAsJsonObject();
// if (res.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
// Set<String> keySet = json.keySet();
// for (String key : keySet) {
//
// }
// return json.getAsJsonObject();
// }
private String postData(String businessName, String funcName, String partnerId, String data)
throws IOException, NoSuchAlgorithmException, InvalidKeyException {
HttpURLConnection conn = null;
URL url = new URL(reqUrl);
conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setRequestMethod("POST");
// conn.setUseCaches(false);
// conn.setInstanceFollowRedirects(true);
conn.setRequestProperty("Content-Type", "application/json");
conn.setRequestProperty("Accept", "application/json");
String timestamp = Long.toString(System.currentTimeMillis());
// String signature = createSignature(partnerSecret, partnerId, timestamp);
String requestId = UUID.randomUUID().toString().replaceAll("-", "");
// conn.setRequestProperty("god-portal-timestamp",timestamp);
// conn.setRequestProperty("god-portal-signature",signature);
// conn.setRequestProperty("god-portal-request-id", requestId);
conn.connect();
OutputStream os = conn.getOutputStream();
os.write(data.getBytes());
os.flush();
os.close();
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
InputStream inputStream = conn.getInputStream();
byte[] bytes = new byte[1024];
int readBytes;
while((readBytes = inputStream.read(bytes)) != -1) {
byteArrayOutputStream.write(bytes, 0, readBytes);
}
bytes = byteArrayOutputStream.toByteArray();
inputStream.close();
conn.disconnect();
return new String(bytes, "utf-8");
}
private String createSignature(String partnerSecret, String partnerId, String timestamp)
throws UnsupportedEncodingException, NoSuchAlgorithmException, InvalidKeyException {
Mac sha256_HMAC = Mac.getInstance("HmacSHA256");
SecretKeySpec secret_key = new SecretKeySpec(partnerSecret.getBytes("UTF-8"), "HmacSHA256");
sha256_HMAC.init(secret_key);
return bytesToHex(sha256_HMAC.doFinal((partnerId + timestamp).getBytes("UTF-8")));
}
private String bytesToHex(byte[] bytes) {
char[] hexChars = new char[bytes.length * 2];
for (int j = 0; j < bytes.length; j++) {
int v = bytes[j] & 0Xff;
hexChars[j * 2] = hexArray[v >>> 4];
hexChars[j * 2 + 1] = hexArray[v & 0x0F];
}
return new String(hexChars);
}
private String signCalc(String apiName, String apiVersion, String apiAccessKey, String apiEcreKey, String apiTimestamp) {
byte[] result = null;
try {
//根据给定的字节数组构造一个密钥,第二参数指定一个密钥算法的名称
SecretKeySpec signinKey = new SecretKeySpec(apiEcreKey.getBytes(), HMAC_SHA1_ALGORITHM);
//生成一个指定 Mac 算法 的 Mac 对象
Mac mac = Mac.getInstance(HMAC_SHA1_ALGORITHM);
//用给定密钥初始化 Mac 对象
mac.init(signinKey);
//完成 Mac 操作
StringBuffer sb = new StringBuffer();
sb.append("_api_access_key="+apiAccessKey+"&_api_name="+apiName+"&_api_timestamp="+apiTimestamp+"&_api_version="+apiVersion);
byte[] rawHmac = mac.doFinal(sb.toString().getBytes());
result = Base64.encodeBase64(rawHmac);
} catch (NoSuchAlgorithmException e) {
System.err.println(e.getMessage());
} catch (InvalidKeyException e) {
System.err.println(e.getMessage());
}
if (null != result) {
return new String(result);
} else {
return null;
}
}
public void yb() {
try {
String timestamp = String.valueOf(System.currentTimeMillis()); // 时间戳
String sign = DigestUtils.md5Hex(appId + appKey + timestamp); // 签名
JSONObject params = new JSONObject(); // 请求参数
params.put("username", username);
params.put("password", password);
params.put("appId", appId);
params.put("timestamp", timestamp);
params.put("sign", sign);
params.put("orderId", "your_order_id");
params.put("totalAmount", "100");
params.put("subject", "your_subject");
params.put("notifyUrl", "your_notify_url");
params.put("returnUrl", "your_return_url");
URL apiUrl = new URL(url);
HttpURLConnection connection = (HttpURLConnection) apiUrl.openConnection();
connection.setRequestMethod("POST"); // 请求方法
connection.setRequestProperty("Content-Type", "application/json;charset=UTF-8"); // 请求头
connection.setDoOutput(true); // 允许输出流
OutputStream outputStream = connection.getOutputStream();
outputStream.write(params.toJSONString().getBytes("UTF-8"));
outputStream.flush();
outputStream.close();
int responseCode = connection.getResponseCode(); // 响应码
if (responseCode == 200) {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
StringBuilder response = new StringBuilder();
String line;
while ((line = bufferedReader.readLine()) != null) {
response.append(line);
}
bufferedReader.close();
System.out.println(response.toString()); // 输出响应结果
}
connection.disconnect();
} catch (Exception e) {
e.printStackTrace();
}
}