repo
stringclasses
1k values
file_url
stringlengths
96
373
file_path
stringlengths
11
294
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
6 values
commit_sha
stringclasses
1k values
retrieved_at
stringdate
2026-01-04 14:45:56
2026-01-04 18:30:23
truncated
bool
2 classes
binarywang/WxJava
https://github.com/binarywang/WxJava/blob/84b5c4d2d0774f800237634e5d0336f53c004fe3/weixin-java-pay/src/main/java/com/github/binarywang/wxpay/v3/SpecEncrypt.java
weixin-java-pay/src/main/java/com/github/binarywang/wxpay/v3/SpecEncrypt.java
package com.github.binarywang.wxpay.v3; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * 敏感信息字段 * @author zhouyognshen **/ @Target({ElementType.FIELD}) @Retention(RetentionPolicy.RUNTIME) public @interface SpecEncrypt { }
java
Apache-2.0
84b5c4d2d0774f800237634e5d0336f53c004fe3
2026-01-04T14:46:39.499027Z
false
binarywang/WxJava
https://github.com/binarywang/WxJava/blob/84b5c4d2d0774f800237634e5d0336f53c004fe3/weixin-java-pay/src/main/java/com/github/binarywang/wxpay/v3/SignatureExec.java
weixin-java-pay/src/main/java/com/github/binarywang/wxpay/v3/SignatureExec.java
package com.github.binarywang.wxpay.v3; import org.apache.http.HttpEntity; import org.apache.http.HttpEntityEnclosingRequest; import org.apache.http.HttpException; import org.apache.http.StatusLine; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpExecutionAware; import org.apache.http.client.methods.HttpRequestWrapper; import org.apache.http.client.protocol.HttpClientContext; import org.apache.http.conn.routing.HttpRoute; import org.apache.http.entity.BufferedHttpEntity; import org.apache.http.entity.ByteArrayEntity; import org.apache.http.impl.execchain.ClientExecChain; import org.apache.http.util.EntityUtils; import java.io.IOException; public class SignatureExec implements ClientExecChain { final ClientExecChain mainExec; final Credentials credentials; final Validator validator; SignatureExec(Credentials credentials, Validator validator, ClientExecChain mainExec) { this.credentials = credentials; this.validator = validator; this.mainExec = mainExec; } protected HttpEntity newRepeatableEntity(HttpEntity entity) throws IOException { byte[] content = EntityUtils.toByteArray(entity); ByteArrayEntity newEntity = new ByteArrayEntity(content); newEntity.setContentEncoding(entity.getContentEncoding()); newEntity.setContentType(entity.getContentType()); return newEntity; } protected void convertToRepeatableResponseEntity(CloseableHttpResponse response) throws IOException { HttpEntity entity = response.getEntity(); if (entity != null && !entity.isRepeatable()) { response.setEntity(newRepeatableEntity(entity)); } } protected void convertToRepeatableRequestEntity(HttpRequestWrapper request) throws IOException { if (request instanceof HttpEntityEnclosingRequest) { HttpEntity entity = ((HttpEntityEnclosingRequest) request).getEntity(); if (entity != null) { ((HttpEntityEnclosingRequest) request).setEntity(new BufferedHttpEntity(entity)); } } } @Override public CloseableHttpResponse execute(HttpRoute route, HttpRequestWrapper request, HttpClientContext context, HttpExecutionAware execAware) throws IOException, HttpException { if (request.getURI().getHost() != null && request.getURI().getHost().endsWith(".mch.weixin.qq.com")) { return executeWithSignature(route, request, context, execAware); } else { return mainExec.execute(route, request, context, execAware); } } private CloseableHttpResponse executeWithSignature(HttpRoute route, HttpRequestWrapper request, HttpClientContext context, HttpExecutionAware execAware) throws IOException, HttpException { // 上传类不需要消耗两次故不做转换 if (!(request.getOriginal() instanceof WechatPayUploadHttpPost)) { convertToRepeatableRequestEntity(request); } // 添加认证信息 request.addHeader("Authorization", credentials.getSchema() + " " + credentials.getToken(request)); // 执行 CloseableHttpResponse response = mainExec.execute(route, request, context, execAware); // 对成功应答验签 StatusLine statusLine = response.getStatusLine(); if (statusLine.getStatusCode() >= 200 && statusLine.getStatusCode() < 300) { convertToRepeatableResponseEntity(response); if (!(request.getOriginal() instanceof WxPayV3DownloadHttpGet)) { if (!validator.validate(response)) { throw new HttpException("应答的微信支付签名验证失败"); } } } return response; } }
java
Apache-2.0
84b5c4d2d0774f800237634e5d0336f53c004fe3
2026-01-04T14:46:39.499027Z
false
binarywang/WxJava
https://github.com/binarywang/WxJava/blob/84b5c4d2d0774f800237634e5d0336f53c004fe3/weixin-java-pay/src/main/java/com/github/binarywang/wxpay/v3/WechatPayUploadHttpPost.java
weixin-java-pay/src/main/java/com/github/binarywang/wxpay/v3/WechatPayUploadHttpPost.java
package com.github.binarywang.wxpay.v3; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.ContentType; import org.apache.http.entity.mime.HttpMultipartMode; import org.apache.http.entity.mime.MultipartEntityBuilder; import java.io.InputStream; import java.net.URI; import java.net.URLConnection; public class WechatPayUploadHttpPost extends HttpPost { private String meta; private WechatPayUploadHttpPost(URI uri, String meta) { super(uri); this.meta = meta; } public String getMeta() { return meta; } public static class Builder { private String fileName; private String fileSha256; private InputStream fileInputStream; private ContentType fileContentType; private URI uri; public Builder(URI uri) { this.uri = uri; } public Builder withImage(String fileName, String fileSha256, InputStream inputStream) { this.fileName = fileName; this.fileSha256 = fileSha256; this.fileInputStream = inputStream; String mimeType = URLConnection.guessContentTypeFromName(fileName); if (mimeType == null) { // guess this is a video uploading this.fileContentType = ContentType.APPLICATION_OCTET_STREAM; } else { this.fileContentType = ContentType.create(mimeType); } return this; } public WechatPayUploadHttpPost build() { if (fileName == null || fileSha256 == null || fileInputStream == null) { throw new IllegalArgumentException("缺少待上传图片文件信息"); } if (uri == null) { throw new IllegalArgumentException("缺少上传图片接口URL"); } String meta = String.format("{\"filename\":\"%s\",\"sha256\":\"%s\"}", fileName, fileSha256); WechatPayUploadHttpPost request = new WechatPayUploadHttpPost(uri, meta); MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create(); entityBuilder.setMode(HttpMultipartMode.RFC6532) .addBinaryBody("file", fileInputStream, fileContentType, fileName) .addTextBody("meta", meta, ContentType.APPLICATION_JSON); request.setEntity(entityBuilder.build()); request.addHeader("Accept", ContentType.APPLICATION_JSON.toString()); return request; } /** * 平台收付通(注销申请)-图片上传-图片上传 * https://pay.weixin.qq.com/docs/partner/apis/ecommerce-cancel/media/upload-media.html * @return WechatPayUploadHttpPost */ public WechatPayUploadHttpPost buildEcommerceAccount() { if (fileName == null || fileSha256 == null || fileInputStream == null) { throw new IllegalArgumentException("缺少待上传图片文件信息"); } if (uri == null) { throw new IllegalArgumentException("缺少上传图片接口URL"); } String meta = String.format("{\"file_name\":\"%s\",\"file_digest\":\"%s\"}", fileName, fileSha256); WechatPayUploadHttpPost request = new WechatPayUploadHttpPost(uri, meta); MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create(); entityBuilder.setMode(HttpMultipartMode.RFC6532) .addBinaryBody("file", fileInputStream, fileContentType, fileName) .addTextBody("meta", meta, ContentType.APPLICATION_JSON); request.setEntity(entityBuilder.build()); request.addHeader("Accept", ContentType.APPLICATION_JSON.toString()); return request; } } }
java
Apache-2.0
84b5c4d2d0774f800237634e5d0336f53c004fe3
2026-01-04T14:46:39.499027Z
false
binarywang/WxJava
https://github.com/binarywang/WxJava/blob/84b5c4d2d0774f800237634e5d0336f53c004fe3/weixin-java-pay/src/main/java/com/github/binarywang/wxpay/v3/util/PemUtils.java
weixin-java-pay/src/main/java/com/github/binarywang/wxpay/v3/util/PemUtils.java
package com.github.binarywang.wxpay.v3.util; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.security.KeyFactory; import java.security.NoSuchAlgorithmException; import java.security.PrivateKey; import java.security.PublicKey; import java.security.cert.CertificateException; import java.security.cert.CertificateExpiredException; import java.security.cert.CertificateFactory; import java.security.cert.CertificateNotYetValidException; import java.security.cert.X509Certificate; import java.security.spec.InvalidKeySpecException; import java.security.spec.PKCS8EncodedKeySpec; import java.security.spec.X509EncodedKeySpec; import java.util.Base64; import me.chanjar.weixin.common.error.WxRuntimeException; public class PemUtils { public static PrivateKey loadPrivateKey(InputStream inputStream) { try { ByteArrayOutputStream array = new ByteArrayOutputStream(); byte[] buffer = new byte[1024]; int length; while ((length = inputStream.read(buffer)) != -1) { array.write(buffer, 0, length); } String privateKey = array.toString("utf-8") .replace("-----BEGIN PRIVATE KEY-----", "") .replace("-----END PRIVATE KEY-----", "") .replaceAll("\\s+", ""); KeyFactory kf = KeyFactory.getInstance("RSA"); return kf.generatePrivate( new PKCS8EncodedKeySpec(Base64.getDecoder().decode(privateKey))); } catch (NoSuchAlgorithmException e) { throw new WxRuntimeException("当前Java环境不支持RSA", e); } catch (InvalidKeySpecException e) { throw new WxRuntimeException("无效的密钥格式"); } catch (IOException e) { throw new WxRuntimeException("无效的密钥"); } } public static X509Certificate loadCertificate(InputStream inputStream) { try { CertificateFactory cf = CertificateFactory.getInstance("X.509"); X509Certificate cert = (X509Certificate) cf.generateCertificate(inputStream); cert.checkValidity(); return cert; } catch (CertificateExpiredException e) { throw new WxRuntimeException("证书已过期", e); } catch (CertificateNotYetValidException e) { throw new WxRuntimeException("证书尚未生效", e); } catch (CertificateException e) { throw new WxRuntimeException("无效的证书", e); } } public static PublicKey loadPublicKey(InputStream inputStream){ try { ByteArrayOutputStream array = new ByteArrayOutputStream(); byte[] buffer = new byte[1024]; int length; while ((length = inputStream.read(buffer)) != -1) { array.write(buffer, 0, length); } String publicKey = array.toString("utf-8") .replace("-----BEGIN PUBLIC KEY-----", "") .replace("-----END PUBLIC KEY-----", "") .replaceAll("\\s+", ""); return KeyFactory.getInstance("RSA") .generatePublic(new X509EncodedKeySpec(Base64.getDecoder().decode(publicKey))); } catch (NoSuchAlgorithmException e) { throw new WxRuntimeException("当前Java环境不支持RSA", e); } catch (InvalidKeySpecException e) { throw new WxRuntimeException("无效的密钥格式"); } catch (IOException e) { throw new WxRuntimeException("无效的密钥"); } } }
java
Apache-2.0
84b5c4d2d0774f800237634e5d0336f53c004fe3
2026-01-04T14:46:39.499027Z
false
binarywang/WxJava
https://github.com/binarywang/WxJava/blob/84b5c4d2d0774f800237634e5d0336f53c004fe3/weixin-java-pay/src/main/java/com/github/binarywang/wxpay/v3/util/AesUtils.java
weixin-java-pay/src/main/java/com/github/binarywang/wxpay/v3/util/AesUtils.java
package com.github.binarywang.wxpay.v3.util; import org.apache.commons.lang3.StringUtils; import javax.crypto.Cipher; import javax.crypto.Mac; import javax.crypto.NoSuchPaddingException; import javax.crypto.spec.GCMParameterSpec; import javax.crypto.spec.SecretKeySpec; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.security.GeneralSecurityException; import java.security.InvalidAlgorithmParameterException; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; import java.util.Base64; import java.util.Map; import java.util.SortedMap; import java.util.TreeMap; public class AesUtils { static final int KEY_LENGTH_BYTE = 32; static final int TAG_LENGTH_BIT = 128; private final byte[] aesKey; public AesUtils(byte[] key) { if (key.length != KEY_LENGTH_BYTE) { throw new IllegalArgumentException("无效的ApiV3Key,长度必须为32个字节"); } this.aesKey = key; } public static byte[] decryptToByte(byte[] nonce, byte[] cipherData, byte[] key) throws GeneralSecurityException { return decryptToByte(null, nonce, cipherData, key); } public static byte[] decryptToByte(byte[] associatedData, byte[] nonce, byte[] cipherData, byte[] key) throws GeneralSecurityException { try { Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding"); SecretKeySpec secretKeySpec = new SecretKeySpec(key, "AES"); GCMParameterSpec spec = new GCMParameterSpec(TAG_LENGTH_BIT, nonce); cipher.init(Cipher.DECRYPT_MODE, secretKeySpec, spec); if (associatedData != null) { cipher.updateAAD(associatedData); } return cipher.doFinal(cipherData); } catch (NoSuchAlgorithmException | NoSuchPaddingException e) { throw new IllegalStateException(e); } catch (InvalidKeyException | InvalidAlgorithmParameterException e) { throw new IllegalArgumentException(e); } } public String decryptToString(byte[] associatedData, byte[] nonce, String ciphertext) throws GeneralSecurityException, IOException { try { Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding"); SecretKeySpec key = new SecretKeySpec(aesKey, "AES"); GCMParameterSpec spec = new GCMParameterSpec(TAG_LENGTH_BIT, nonce); cipher.init(Cipher.DECRYPT_MODE, key, spec); cipher.updateAAD(associatedData); return new String(cipher.doFinal(Base64.getDecoder().decode(StringUtils.remove(ciphertext, " "))), StandardCharsets.UTF_8); } catch (NoSuchAlgorithmException | NoSuchPaddingException e) { throw new IllegalStateException(e); } catch (InvalidKeyException | InvalidAlgorithmParameterException e) { throw new IllegalArgumentException(e); } } public static String decryptToString(String associatedData, String nonce, String ciphertext, String apiV3Key) throws GeneralSecurityException, IOException { try { Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding"); SecretKeySpec key = new SecretKeySpec(apiV3Key.getBytes(StandardCharsets.UTF_8), "AES"); GCMParameterSpec spec = new GCMParameterSpec(TAG_LENGTH_BIT, nonce.getBytes(StandardCharsets.UTF_8)); cipher.init(Cipher.DECRYPT_MODE, key, spec); cipher.updateAAD(associatedData.getBytes(StandardCharsets.UTF_8)); return new String(cipher.doFinal(Base64.getDecoder().decode(ciphertext)), StandardCharsets.UTF_8); } catch (NoSuchAlgorithmException | NoSuchPaddingException e) { throw new IllegalStateException(e); } catch (InvalidKeyException | InvalidAlgorithmParameterException e) { throw new IllegalArgumentException(e); } } public static String createSign(Map<String, String> map, String mchKey) { Map<String, String> params = map; SortedMap<String, String> sortedMap = new TreeMap<>(params); StringBuilder toSign = new StringBuilder(); for (String key : sortedMap.keySet()) { String value = params.get(key); if ("sign".equals(key) || StringUtils.isEmpty(value)) { continue; } toSign.append(key).append("=").append(value).append("&"); } toSign.append("key=" + mchKey); return HMACSHA256(toSign.toString(), mchKey); } public static String HMACSHA256(String data, String key) { try { Mac sha256_HMAC = Mac.getInstance("HmacSHA256"); SecretKeySpec secret_key = new SecretKeySpec(key.getBytes(StandardCharsets.UTF_8), "HmacSHA256"); sha256_HMAC.init(secret_key); byte[] array = sha256_HMAC.doFinal(data.getBytes(StandardCharsets.UTF_8)); StringBuilder sb = new StringBuilder(); for (byte item : array) { sb.append(Integer.toHexString((item & 0xFF) | 0x100).substring(1, 3)); } return sb.toString().toUpperCase(); } catch (Exception e) { e.printStackTrace(); return null; } } }
java
Apache-2.0
84b5c4d2d0774f800237634e5d0336f53c004fe3
2026-01-04T14:46:39.499027Z
false
binarywang/WxJava
https://github.com/binarywang/WxJava/blob/84b5c4d2d0774f800237634e5d0336f53c004fe3/weixin-java-pay/src/main/java/com/github/binarywang/wxpay/v3/util/SignUtils.java
weixin-java-pay/src/main/java/com/github/binarywang/wxpay/v3/util/SignUtils.java
package com.github.binarywang.wxpay.v3.util; import me.chanjar.weixin.common.error.WxRuntimeException; import java.security.*; import java.util.Base64; import java.util.Random; /** * @author cloudx */ public class SignUtils { public static String sign(String string, PrivateKey privateKey) { try { Signature sign = Signature.getInstance("SHA256withRSA"); sign.initSign(privateKey); sign.update(string.getBytes()); return Base64.getEncoder().encodeToString(sign.sign()); } catch (NoSuchAlgorithmException e) { throw new WxRuntimeException("当前Java环境不支持SHA256withRSA", e); } catch (SignatureException e) { throw new WxRuntimeException("签名计算失败", e); } catch (InvalidKeyException e) { throw new WxRuntimeException("无效的私钥", e); } } /** * 随机生成32位字符串. */ public static String genRandomStr() { return genRandomStr(32); } private static volatile Random random; private static Random getRandom() { if (random == null) { synchronized (SignUtils.class) { if (random == null) { random = new Random(); } } } return random; } /** * 生成随机字符串 * * @param length 字符串长度 * @return 随机字符串 */ public static String genRandomStr(int length) { String base = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; Random r = getRandom(); StringBuilder sb = new StringBuilder(); for (int i = 0; i < length; i++) { int number = r.nextInt(base.length()); sb.append(base.charAt(number)); } return sb.toString(); } }
java
Apache-2.0
84b5c4d2d0774f800237634e5d0336f53c004fe3
2026-01-04T14:46:39.499027Z
false
binarywang/WxJava
https://github.com/binarywang/WxJava/blob/84b5c4d2d0774f800237634e5d0336f53c004fe3/weixin-java-pay/src/main/java/com/github/binarywang/wxpay/v3/util/RsaCryptoUtil.java
weixin-java-pay/src/main/java/com/github/binarywang/wxpay/v3/util/RsaCryptoUtil.java
package com.github.binarywang.wxpay.v3.util; import com.github.binarywang.wxpay.exception.WxPayException; import com.github.binarywang.wxpay.v3.SpecEncrypt; import me.chanjar.weixin.common.error.WxRuntimeException; import javax.crypto.BadPaddingException; import javax.crypto.Cipher; import javax.crypto.IllegalBlockSizeException; import javax.crypto.NoSuchPaddingException; import java.lang.reflect.Field; import java.nio.charset.StandardCharsets; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; import java.security.PrivateKey; import java.security.cert.X509Certificate; import java.util.Base64; import java.util.Collection; /** * 微信支付敏感信息加密 * 文档见: https://wechatpay-api.gitbook.io/wechatpay-api-v3/qian-ming-zhi-nan-1/min-gan-xin-xi-jia-mi * * @author zhouyongshen **/ public class RsaCryptoUtil { static String JAVA_LANG_STRING = "java.lang.String"; public static void encryptFields(Object encryptObject, X509Certificate certificate) throws WxPayException { try { encryptField(encryptObject, certificate); } catch (Exception e) { throw new WxPayException("敏感信息加密失败", e); } } private static void encryptField(Object encryptObject, X509Certificate certificate) throws IllegalAccessException, IllegalBlockSizeException { Class<?> infoClass = encryptObject.getClass(); Field[] infoFieldArray = infoClass.getDeclaredFields(); for (Field field : infoFieldArray) { if (field.isAnnotationPresent(SpecEncrypt.class)) { //字段使用了@SpecEncrypt进行标识 if (field.getType().getTypeName().equals(JAVA_LANG_STRING)) { field.setAccessible(true); Object oldValue = field.get(encryptObject); if (oldValue != null) { String oldStr = (String) oldValue; if (!oldStr.trim().isEmpty()) { field.set(encryptObject, encryptOAEP(oldStr, certificate)); } } } else { field.setAccessible(true); Object obj = field.get(encryptObject); if (obj == null) { continue; } if (obj instanceof Collection<?>) { Collection<?> collection = (Collection<?>) obj; for (Object o : collection) { if (o != null) { encryptField(o, certificate); } } } else { encryptField(obj, certificate); } } } } } public static String encryptOAEP(String message, X509Certificate certificate) throws IllegalBlockSizeException { try { Cipher cipher = Cipher.getInstance("RSA/ECB/OAEPWithSHA-1AndMGF1Padding"); cipher.init(Cipher.ENCRYPT_MODE, certificate.getPublicKey()); byte[] data = message.getBytes(StandardCharsets.UTF_8); byte[] ciphertext = cipher.doFinal(data); return Base64.getEncoder().encodeToString(ciphertext); } catch (NoSuchAlgorithmException | NoSuchPaddingException e) { throw new WxRuntimeException("当前Java环境不支持RSA v1.5/OAEP", e); } catch (InvalidKeyException e) { throw new IllegalArgumentException("无效的证书", e); } catch (IllegalBlockSizeException | BadPaddingException e) { throw new IllegalBlockSizeException("加密原串的长度不能超过214字节"); } } public static String decryptOAEP(String ciphertext, PrivateKey privateKey) throws BadPaddingException { try { Cipher cipher = Cipher.getInstance("RSA/ECB/OAEPWithSHA-1AndMGF1Padding"); cipher.init(Cipher.DECRYPT_MODE, privateKey); byte[] data = Base64.getDecoder().decode(ciphertext); return new String(cipher.doFinal(data), StandardCharsets.UTF_8); } catch (NoSuchPaddingException | NoSuchAlgorithmException e) { throw new WxRuntimeException("当前Java环境不支持RSA v1.5/OAEP", e); } catch (InvalidKeyException e) { throw new IllegalArgumentException("无效的私钥", e); } catch (BadPaddingException | IllegalBlockSizeException e) { throw new BadPaddingException("解密失败"); } } }
java
Apache-2.0
84b5c4d2d0774f800237634e5d0336f53c004fe3
2026-01-04T14:46:39.499027Z
false
binarywang/WxJava
https://github.com/binarywang/WxJava/blob/84b5c4d2d0774f800237634e5d0336f53c004fe3/weixin-java-pay/src/main/java/com/github/binarywang/wxpay/v3/auth/WxPayValidator.java
weixin-java-pay/src/main/java/com/github/binarywang/wxpay/v3/auth/WxPayValidator.java
package com.github.binarywang.wxpay.v3.auth; import com.github.binarywang.wxpay.v3.Validator; import lombok.extern.slf4j.Slf4j; import org.apache.http.Header; import org.apache.http.HttpEntity; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.entity.ContentType; import org.apache.http.util.EntityUtils; import java.io.IOException; import java.nio.charset.StandardCharsets; /** * @author spvycf & F00lish */ @Slf4j public class WxPayValidator implements Validator { private final Verifier verifier; public WxPayValidator(Verifier verifier) { this.verifier = verifier; } @Override public final boolean validate(CloseableHttpResponse response) throws IOException { if (!ContentType.APPLICATION_JSON.getMimeType().equals(ContentType.parse(String.valueOf(response.getFirstHeader( "Content-Type").getValue())).getMimeType())) { return true; } Header serialNo = response.getFirstHeader("Wechatpay-Serial"); Header sign = response.getFirstHeader("Wechatpay-Signature"); Header timestamp = response.getFirstHeader("Wechatpay-TimeStamp"); Header nonce = response.getFirstHeader("Wechatpay-Nonce"); // todo: check timestamp if (timestamp == null || nonce == null || serialNo == null || sign == null) { return false; } String message = buildMessage(response); return verifier.verify(serialNo.getValue(), message.getBytes(StandardCharsets.UTF_8), sign.getValue()); } protected final String buildMessage(CloseableHttpResponse response) throws IOException { String timestamp = response.getFirstHeader("Wechatpay-TimeStamp").getValue(); String nonce = response.getFirstHeader("Wechatpay-Nonce").getValue(); String body = getResponseBody(response); return timestamp + "\n" + nonce + "\n" + body + "\n"; } protected final String getResponseBody(CloseableHttpResponse response) throws IOException { HttpEntity entity = response.getEntity(); return (entity != null && entity.isRepeatable()) ? EntityUtils.toString(entity) : ""; } }
java
Apache-2.0
84b5c4d2d0774f800237634e5d0336f53c004fe3
2026-01-04T14:46:39.499027Z
false
binarywang/WxJava
https://github.com/binarywang/WxJava/blob/84b5c4d2d0774f800237634e5d0336f53c004fe3/weixin-java-pay/src/main/java/com/github/binarywang/wxpay/v3/auth/Signer.java
weixin-java-pay/src/main/java/com/github/binarywang/wxpay/v3/auth/Signer.java
package com.github.binarywang.wxpay.v3.auth; public interface Signer { SignatureResult sign(byte[] message); class SignatureResult { String sign; String certificateSerialNumber; public SignatureResult(String sign, String serialNumber) { this.sign = sign; this.certificateSerialNumber = serialNumber; } } }
java
Apache-2.0
84b5c4d2d0774f800237634e5d0336f53c004fe3
2026-01-04T14:46:39.499027Z
false
binarywang/WxJava
https://github.com/binarywang/WxJava/blob/84b5c4d2d0774f800237634e5d0336f53c004fe3/weixin-java-pay/src/main/java/com/github/binarywang/wxpay/v3/auth/PrivateKeySigner.java
weixin-java-pay/src/main/java/com/github/binarywang/wxpay/v3/auth/PrivateKeySigner.java
package com.github.binarywang.wxpay.v3.auth; import me.chanjar.weixin.common.error.WxRuntimeException; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; import java.security.PrivateKey; import java.security.Signature; import java.security.SignatureException; import java.util.Base64; public class PrivateKeySigner implements Signer { private String certificateSerialNumber; private PrivateKey privateKey; public PrivateKeySigner(String serialNumber, PrivateKey privateKey) { this.certificateSerialNumber = serialNumber; this.privateKey = privateKey; } @Override public SignatureResult sign(byte[] message) { try { Signature sign = Signature.getInstance("SHA256withRSA"); sign.initSign(privateKey); sign.update(message); return new SignatureResult( Base64.getEncoder().encodeToString(sign.sign()), certificateSerialNumber); } catch (NoSuchAlgorithmException e) { throw new WxRuntimeException("当前Java环境不支持SHA256withRSA", e); } catch (SignatureException e) { throw new WxRuntimeException("签名计算失败", e); } catch (InvalidKeyException e) { throw new WxRuntimeException("无效的私钥", e); } } }
java
Apache-2.0
84b5c4d2d0774f800237634e5d0336f53c004fe3
2026-01-04T14:46:39.499027Z
false
binarywang/WxJava
https://github.com/binarywang/WxJava/blob/84b5c4d2d0774f800237634e5d0336f53c004fe3/weixin-java-pay/src/main/java/com/github/binarywang/wxpay/v3/auth/Verifier.java
weixin-java-pay/src/main/java/com/github/binarywang/wxpay/v3/auth/Verifier.java
package com.github.binarywang.wxpay.v3.auth; import java.security.cert.X509Certificate; public interface Verifier { boolean verify(String serialNumber, byte[] message, String signature); X509Certificate getValidCertificate(); default void setOtherVerifier(Verifier verifier) {}; }
java
Apache-2.0
84b5c4d2d0774f800237634e5d0336f53c004fe3
2026-01-04T14:46:39.499027Z
false
binarywang/WxJava
https://github.com/binarywang/WxJava/blob/84b5c4d2d0774f800237634e5d0336f53c004fe3/weixin-java-pay/src/main/java/com/github/binarywang/wxpay/v3/auth/PublicCertificateVerifier.java
weixin-java-pay/src/main/java/com/github/binarywang/wxpay/v3/auth/PublicCertificateVerifier.java
package com.github.binarywang.wxpay.v3.auth; import java.security.*; import java.security.cert.X509Certificate; import java.util.Base64; import me.chanjar.weixin.common.error.WxRuntimeException; public class PublicCertificateVerifier implements Verifier{ private final PublicKey publicKey; private Verifier certificateVerifier; private final X509PublicCertificate publicCertificate; public PublicCertificateVerifier(PublicKey publicKey, String publicId) { this.publicKey = publicKey; this.publicCertificate = new X509PublicCertificate(publicKey, publicId); } public void setOtherVerifier(Verifier verifier) { this.certificateVerifier = verifier; } @Override public boolean verify(String serialNumber, byte[] message, String signature) { // 如果序列号不为空且不包含"PUB_KEY_ID"且有证书验证器,先尝试证书验证 if (serialNumber != null && !serialNumber.contains("PUB_KEY_ID") && this.certificateVerifier != null) { try { if (this.certificateVerifier.verify(serialNumber, message, signature)) { return true; } } catch (Exception e) { // 证书验证失败,继续尝试公钥验证 } } // 使用公钥验证(兜底方案,适用于公钥转账等场景) try { Signature sign = Signature.getInstance("SHA256withRSA"); sign.initVerify(publicKey); sign.update(message); return sign.verify(Base64.getDecoder().decode(signature)); } catch (NoSuchAlgorithmException e) { throw new WxRuntimeException("当前Java环境不支持SHA256withRSA", e); } catch (SignatureException e) { throw new WxRuntimeException("签名验证过程发生了错误", e); } catch (InvalidKeyException e) { throw new WxRuntimeException("无效的证书", e); } } @Override public X509Certificate getValidCertificate() { return this.publicCertificate; } }
java
Apache-2.0
84b5c4d2d0774f800237634e5d0336f53c004fe3
2026-01-04T14:46:39.499027Z
false
binarywang/WxJava
https://github.com/binarywang/WxJava/blob/84b5c4d2d0774f800237634e5d0336f53c004fe3/weixin-java-pay/src/main/java/com/github/binarywang/wxpay/v3/auth/X509PublicCertificate.java
weixin-java-pay/src/main/java/com/github/binarywang/wxpay/v3/auth/X509PublicCertificate.java
package com.github.binarywang.wxpay.v3.auth; import java.math.BigInteger; import java.security.*; import java.security.cert.*; import java.util.Collections; import java.util.Date; import java.util.Set; public class X509PublicCertificate extends X509Certificate { private final PublicKey publicKey; private final String publicId; public X509PublicCertificate(PublicKey publicKey, String publicId) { this.publicKey = publicKey; this.publicId = publicId; } @Override public PublicKey getPublicKey() { return this.publicKey; } @Override public BigInteger getSerialNumber() { return new BigInteger(publicId.replace("PUB_KEY_ID_", ""), 16); } @Override public void checkValidity() throws CertificateExpiredException, CertificateNotYetValidException { } @Override public void checkValidity(Date date) throws CertificateExpiredException, CertificateNotYetValidException { } @Override public int getVersion() { return 0; } @Override public Principal getIssuerDN() { return null; } @Override public Principal getSubjectDN() { return null; } @Override public Date getNotBefore() { return null; } @Override public Date getNotAfter() { return null; } @Override public byte[] getTBSCertificate() throws CertificateEncodingException { return new byte[0]; } @Override public byte[] getSignature() { return new byte[0]; } @Override public String getSigAlgName() { return ""; } @Override public String getSigAlgOID() { return ""; } @Override public byte[] getSigAlgParams() { return new byte[0]; } @Override public boolean[] getIssuerUniqueID() { return new boolean[0]; } @Override public boolean[] getSubjectUniqueID() { return new boolean[0]; } @Override public boolean[] getKeyUsage() { return new boolean[0]; } @Override public int getBasicConstraints() { return 0; } @Override public byte[] getEncoded() throws CertificateEncodingException { return new byte[0]; } @Override public void verify(PublicKey key) throws CertificateException, NoSuchAlgorithmException, InvalidKeyException, NoSuchProviderException, SignatureException { } @Override public void verify(PublicKey key, String sigProvider) throws CertificateException, NoSuchAlgorithmException, InvalidKeyException, NoSuchProviderException, SignatureException { } @Override public String toString() { return ""; } @Override public boolean hasUnsupportedCriticalExtension() { return false; } @Override public Set<String> getCriticalExtensionOIDs() { return Collections.emptySet(); } @Override public Set<String> getNonCriticalExtensionOIDs() { return Collections.emptySet(); } @Override public byte[] getExtensionValue(String oid) { return new byte[0]; } }
java
Apache-2.0
84b5c4d2d0774f800237634e5d0336f53c004fe3
2026-01-04T14:46:39.499027Z
false
binarywang/WxJava
https://github.com/binarywang/WxJava/blob/84b5c4d2d0774f800237634e5d0336f53c004fe3/weixin-java-pay/src/main/java/com/github/binarywang/wxpay/v3/auth/WxPayCredentials.java
weixin-java-pay/src/main/java/com/github/binarywang/wxpay/v3/auth/WxPayCredentials.java
package com.github.binarywang.wxpay.v3.auth; import com.github.binarywang.wxpay.v3.Credentials; import com.github.binarywang.wxpay.v3.WechatPayUploadHttpPost; import lombok.extern.slf4j.Slf4j; import org.apache.http.HttpEntityEnclosingRequest; import org.apache.http.client.methods.HttpRequestWrapper; import org.apache.http.util.EntityUtils; import java.io.IOException; import java.net.URI; import java.nio.charset.StandardCharsets; import java.security.SecureRandom; @Slf4j public class WxPayCredentials implements Credentials { private static final String SYMBOLS = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; private static final SecureRandom RANDOM = new SecureRandom(); protected String merchantId; protected Signer signer; public WxPayCredentials(String merchantId, Signer signer) { this.merchantId = merchantId; this.signer = signer; } public String getMerchantId() { return merchantId; } protected long generateTimestamp() { return System.currentTimeMillis() / 1000; } protected String generateNonceStr() { char[] nonceChars = new char[32]; for (int index = 0; index < nonceChars.length; ++index) { nonceChars[index] = SYMBOLS.charAt(RANDOM.nextInt(SYMBOLS.length())); } return new String(nonceChars); } @Override public final String getSchema() { return "WECHATPAY2-SHA256-RSA2048"; } @Override public final String getToken(HttpRequestWrapper request) throws IOException { String nonceStr = generateNonceStr(); long timestamp = generateTimestamp(); String message = buildMessage(nonceStr, timestamp, request); log.debug("authorization message=[{}]", message); Signer.SignatureResult signature = signer.sign(message.getBytes(StandardCharsets.UTF_8)); String token = "mchid=\"" + getMerchantId() + "\"," + "nonce_str=\"" + nonceStr + "\"," + "timestamp=\"" + timestamp + "\"," + "serial_no=\"" + signature.certificateSerialNumber + "\"," + "signature=\"" + signature.sign + "\""; log.debug("authorization token=[{}]", token); return token; } protected final String buildMessage(String nonce, long timestamp, HttpRequestWrapper request) throws IOException { URI uri = request.getURI(); String canonicalUrl = uri.getRawPath(); if (uri.getQuery() != null) { canonicalUrl += "?" + uri.getRawQuery(); } String body = ""; // PATCH,POST,PUT if (request.getOriginal() instanceof WechatPayUploadHttpPost) { body = ((WechatPayUploadHttpPost) request.getOriginal()).getMeta(); } else if (request instanceof HttpEntityEnclosingRequest) { body = EntityUtils.toString(((HttpEntityEnclosingRequest) request).getEntity()); } return request.getRequestLine().getMethod() + "\n" + canonicalUrl + "\n" + timestamp + "\n" + nonce + "\n" + body + "\n"; } }
java
Apache-2.0
84b5c4d2d0774f800237634e5d0336f53c004fe3
2026-01-04T14:46:39.499027Z
false
binarywang/WxJava
https://github.com/binarywang/WxJava/blob/84b5c4d2d0774f800237634e5d0336f53c004fe3/weixin-java-pay/src/main/java/com/github/binarywang/wxpay/v3/auth/CertificatesVerifier.java
weixin-java-pay/src/main/java/com/github/binarywang/wxpay/v3/auth/CertificatesVerifier.java
package com.github.binarywang.wxpay.v3.auth; import me.chanjar.weixin.common.error.WxRuntimeException; import java.math.BigInteger; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; import java.security.Signature; import java.security.SignatureException; import java.security.cert.CertificateExpiredException; import java.security.cert.CertificateNotYetValidException; import java.security.cert.X509Certificate; import java.util.Base64; import java.util.HashMap; import java.util.List; import java.util.NoSuchElementException; public class CertificatesVerifier implements Verifier { private final HashMap<BigInteger, X509Certificate> certificates = new HashMap<>(); public CertificatesVerifier(List<X509Certificate> list) { for (X509Certificate item : list) { certificates.put(item.getSerialNumber(), item); } } private boolean verify(X509Certificate certificate, byte[] message, String signature) { try { Signature sign = Signature.getInstance("SHA256withRSA"); sign.initVerify(certificate); sign.update(message); return sign.verify(Base64.getDecoder().decode(signature)); } catch (NoSuchAlgorithmException e) { throw new WxRuntimeException("当前Java环境不支持SHA256withRSA", e); } catch (SignatureException e) { throw new WxRuntimeException("签名验证过程发生了错误", e); } catch (InvalidKeyException e) { throw new WxRuntimeException("无效的证书", e); } } @Override public boolean verify(String serialNumber, byte[] message, String signature) { BigInteger val = new BigInteger(serialNumber, 16); return certificates.containsKey(val) && verify(certificates.get(val), message, signature); } @Override public X509Certificate getValidCertificate() { for (X509Certificate x509Cert : certificates.values()) { try { x509Cert.checkValidity(); return x509Cert; } catch (CertificateExpiredException | CertificateNotYetValidException e) { continue; } } throw new NoSuchElementException("没有有效的微信支付平台证书"); } }
java
Apache-2.0
84b5c4d2d0774f800237634e5d0336f53c004fe3
2026-01-04T14:46:39.499027Z
false
binarywang/WxJava
https://github.com/binarywang/WxJava/blob/84b5c4d2d0774f800237634e5d0336f53c004fe3/weixin-java-pay/src/main/java/com/github/binarywang/wxpay/v3/auth/AutoUpdateCertificatesVerifier.java
weixin-java-pay/src/main/java/com/github/binarywang/wxpay/v3/auth/AutoUpdateCertificatesVerifier.java
package com.github.binarywang.wxpay.v3.auth; import com.github.binarywang.wxpay.config.WxPayHttpProxy; import com.github.binarywang.wxpay.util.HttpProxyUtils; import com.github.binarywang.wxpay.v3.Credentials; import com.github.binarywang.wxpay.v3.WxPayV3HttpClientBuilder; import com.github.binarywang.wxpay.v3.util.AesUtils; import com.github.binarywang.wxpay.v3.util.PemUtils; import com.google.gson.JsonArray; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import lombok.Getter; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import me.chanjar.weixin.common.error.WxRuntimeException; import me.chanjar.weixin.common.util.json.GsonParser; import org.apache.http.HttpStatus; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.util.EntityUtils; import java.io.ByteArrayInputStream; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.security.GeneralSecurityException; import java.security.cert.CertificateExpiredException; import java.security.cert.CertificateNotYetValidException; import java.security.cert.X509Certificate; import java.time.Instant; import java.time.temporal.ChronoUnit; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Optional; import java.util.concurrent.locks.ReentrantLock; /** * 在原有CertificatesVerifier基础上,增加自动更新证书功能 * * @author doger.wang * @author Long Yu */ @Slf4j public class AutoUpdateCertificatesVerifier implements Verifier { /** * 证书下载地址 */ private static final String CERT_DOWNLOAD_PATH = "/v3/certificates"; /** * 上次更新时间 */ private volatile Instant instant; /** * 证书更新间隔时间,单位为分钟 */ private final int minutesInterval; private CertificatesVerifier verifier; private final Credentials credentials; private final byte[] apiV3Key; private String payBaseUrl ; private final ReentrantLock lock = new ReentrantLock(); /** * 微信支付代理对象 */ private WxPayHttpProxy wxPayHttpProxy; /** * 时间间隔枚举,支持一小时、六小时以及十二小时 */ @Getter @RequiredArgsConstructor public enum TimeInterval { /** * 一小时 */ OneHour(60), /** * 六小时 */ SixHours(60 * 6), /** * 十二小时 */ TwelveHours(60 * 12); private final int minutes; } public AutoUpdateCertificatesVerifier(Credentials credentials, byte[] apiV3Key, String payBaseUrl) { this(credentials, apiV3Key, TimeInterval.OneHour.getMinutes(), payBaseUrl); } public AutoUpdateCertificatesVerifier(Credentials credentials, byte[] apiV3Key, int minutesInterval, String payBaseUrl) { this(credentials, apiV3Key, minutesInterval, payBaseUrl, null); } public AutoUpdateCertificatesVerifier(Credentials credentials, byte[] apiV3Key, int minutesInterval, String payBaseUrl, WxPayHttpProxy wxPayHttpProxy) { this.credentials = credentials; this.apiV3Key = apiV3Key; this.minutesInterval = minutesInterval; this.payBaseUrl = payBaseUrl; this.wxPayHttpProxy = wxPayHttpProxy; //构造时更新证书 try { autoUpdateCert(); instant = Instant.now(); } catch (IOException | GeneralSecurityException e) { throw new WxRuntimeException(e); } } @Override public boolean verify(String serialNumber, byte[] message, String signature) { checkAndAutoUpdateCert(); return verifier.verify(serialNumber, message, signature); } /** * 检查证书是否在有效期内,如果不在有效期内则进行更新 */ private void checkAndAutoUpdateCert() { if (instant == null || instant.plus(minutesInterval, ChronoUnit.MINUTES).compareTo(Instant.now()) <= 0) { if (lock.tryLock()) { try { autoUpdateCert(); //更新时间 instant = Instant.now(); } catch (GeneralSecurityException | IOException e) { log.warn("Auto update cert failed, exception = {}", e); } finally { lock.unlock(); } } } } private void autoUpdateCert() throws IOException, GeneralSecurityException { WxPayV3HttpClientBuilder wxPayV3HttpClientBuilder = WxPayV3HttpClientBuilder.create() .withCredentials(credentials) .withValidator(verifier == null ? response -> true : new WxPayValidator(verifier)); //调用自定义扩展设置设置HTTP PROXY对象 HttpProxyUtils.initHttpProxy(wxPayV3HttpClientBuilder,this.wxPayHttpProxy); //增加自定义扩展点,子类可以设置其他构造参数 this.customHttpClientBuilder(wxPayV3HttpClientBuilder); CloseableHttpClient httpClient = wxPayV3HttpClientBuilder.build(); HttpGet httpGet = new HttpGet(this.payBaseUrl + CERT_DOWNLOAD_PATH); httpGet.addHeader("Accept", "application/json"); CloseableHttpResponse response = httpClient.execute(httpGet); int statusCode = response.getStatusLine().getStatusCode(); String body = EntityUtils.toString(response.getEntity()); if (statusCode == HttpStatus.SC_OK) { List<X509Certificate> newCertList = deserializeToCerts(apiV3Key, body); if (newCertList.isEmpty()) { throw new WxRuntimeException("Cert list is empty"); } this.verifier = new CertificatesVerifier(newCertList); } else { log.warn("Auto update cert failed, statusCode = {},body = {}", statusCode, body); throw new WxRuntimeException(this.getErrorMsg(body)); } } /** * 子类可以自定义添加Http client builder的信息 * @param builder httpclient构造器 */ public void customHttpClientBuilder(WxPayV3HttpClientBuilder builder) { } /** * 反序列化证书并解密 */ private List<X509Certificate> deserializeToCerts(byte[] apiV3Key, String body) throws GeneralSecurityException, IOException { AesUtils aesUtils = new AesUtils(apiV3Key); final JsonObject json = GsonParser.parse(body); final JsonArray dataNode = json.getAsJsonArray("data"); if (dataNode == null) { return Collections.emptyList(); } List<X509Certificate> newCertList = new ArrayList<>(); for (int i = 0, count = dataNode.size(); i < count; i++) { final JsonObject encryptCertificateNode = ((JsonObject) dataNode.get(i)).getAsJsonObject("encrypt_certificate"); //解密 String cert = aesUtils.decryptToString( encryptCertificateNode.get("associated_data").toString().replaceAll("\"", "") .getBytes(StandardCharsets.UTF_8), encryptCertificateNode.get("nonce").toString().replaceAll("\"", "") .getBytes(StandardCharsets.UTF_8), encryptCertificateNode.get("ciphertext").toString().replaceAll("\"", "")); X509Certificate x509Cert = PemUtils .loadCertificate(new ByteArrayInputStream(cert.getBytes(StandardCharsets.UTF_8))); try { x509Cert.checkValidity(); } catch (CertificateExpiredException | CertificateNotYetValidException e) { continue; } newCertList.add(x509Cert); } return newCertList; } @Override public X509Certificate getValidCertificate() { checkAndAutoUpdateCert(); return verifier.getValidCertificate(); } private String getErrorMsg(String body) { return Optional .ofNullable(GsonParser.parse(body).getAsJsonObject()) .map(resp -> resp.get("message")) .map(JsonElement::getAsString) .orElse("update cert failed"); } }
java
Apache-2.0
84b5c4d2d0774f800237634e5d0336f53c004fe3
2026-01-04T14:46:39.499027Z
false
binarywang/WxJava
https://github.com/binarywang/WxJava/blob/84b5c4d2d0774f800237634e5d0336f53c004fe3/weixin-java-common/src/test/java/me/chanjar/weixin/common/util/XmlUtilsTest.java
weixin-java-common/src/test/java/me/chanjar/weixin/common/util/XmlUtilsTest.java
package me.chanjar.weixin.common.util; import org.testng.annotations.Test; import java.util.List; import java.util.Map; import static org.assertj.core.api.Assertions.assertThat; /** * <pre> * * Created by Binary Wang on 2018/11/4. * </pre> * * @author <a href="https://github.com/binarywang">Binary Wang</a> */ public class XmlUtilsTest { @Test(expectedExceptions = {RuntimeException.class}) public void testXml2Map_xxe() { String xml = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n" + "<!DOCTYPE test [\n" + "<!ENTITY xxe SYSTEM \"file:///etc/passwd\">\n" + "<!ENTITY xxe2 SYSTEM \"http://localhost/test.php\">\n" + "]>\n" + "<xml></xml>"; XmlUtils.xml2Map(xml); } @Test public void testXml2Map() { String xml = "<xml>\n" + "<CopyrightCheckResult>\n" + "<Count>2</Count>\n" + "<ResultList>\n" + "<item>\n" + "<ArticleIdx>1</ArticleIdx>\n" + "<UserDeclareState>0</UserDeclareState>\n" + "<AuditState>2</AuditState>\n" + "<OriginalArticleUrl><![CDATA[Url_1]]></OriginalArticleUrl>\n" + "<OriginalArticleType>1</OriginalArticleType>\n" + "<CanReprint>1</CanReprint>\n" + "<NeedReplaceContent>1</NeedReplaceContent>\n" + "<NeedShowReprintSource>1</NeedShowReprintSource>\n" + "</item>\n" + "<item>\n" + "<ArticleIdx>2</ArticleIdx>\n" + "<UserDeclareState>0</UserDeclareState>\n" + "<AuditState>2</AuditState>\n" + "<OriginalArticleUrl><![CDATA[Url_2]]></OriginalArticleUrl>\n" + "<OriginalArticleType>1</OriginalArticleType>\n" + "<CanReprint>1</CanReprint>\n" + "<NeedReplaceContent>1</NeedReplaceContent>\n" + "<NeedShowReprintSource>1</NeedShowReprintSource>\n" + "</item>\n" + "</ResultList>\n" + "<CheckState>2</CheckState>\n" + "</CopyrightCheckResult>\n" + "</xml>"; final Map<String, Object> map = XmlUtils.xml2Map(xml); assertThat(map).isNotNull(); final Map<String, Object> copyrightCheckResult = (Map<String, Object>) map.get("CopyrightCheckResult"); List<Map<String, Object>> resultList = (List<Map<String, Object>>) ((Map<String, Object>) copyrightCheckResult.get("ResultList")).get("item"); assertThat(copyrightCheckResult) .isNotNull() .containsEntry("Count", "2") .containsEntry("CheckState", "2"); assertThat(resultList.get(0)).containsEntry("ArticleIdx", "1") .containsEntry("UserDeclareState", "0") .containsEntry("AuditState", "2") .containsEntry("OriginalArticleUrl", "Url_1") .containsEntry("OriginalArticleType", "1") .containsEntry("CanReprint", "1") .containsEntry("NeedReplaceContent", "1") .containsEntry("NeedShowReprintSource", "1"); assertThat(resultList.get(1)).containsEntry("ArticleIdx", "2") .containsEntry("UserDeclareState", "0") .containsEntry("AuditState", "2") .containsEntry("OriginalArticleUrl", "Url_2") .containsEntry("OriginalArticleType", "1") .containsEntry("CanReprint", "1") .containsEntry("NeedReplaceContent", "1") .containsEntry("NeedShowReprintSource", "1"); } @Test public void testXml2Map_another() { String xml = "<xml> <ToUserName><![CDATA[gh_4d00ed8d6399]]></ToUserName> <FromUserName><![CDATA[oV5CrjpxgaGXNHIQigzNlgLTnwic]]></FromUserName> <CreateTime>1481013459</CreateTime> <MsgType><![CDATA[event]]></MsgType> <Event><![CDATA[PUBLISHJOBFINISH]]></Event> <PublishEventInfo> <publish_id>2247503051</publish_id> <publish_status>0</publish_status> <article_id><![CDATA[b5O2OUs25HBxRceL7hfReg-U9QGeq9zQjiDvy WP4Hq4]]></article_id> <article_detail> <count>1</count> <item> <idx>1</idx> <article_url><![CDATA[ARTICLE_URL]]></article_url> </item> <item> <idx>2</idx> <article_url><![CDATA[ARTICLE_URL_2]]></article_url> </item> </article_detail> </PublishEventInfo> </xml>"; final Map<String, Object> map = XmlUtils.xml2Map(xml); assertThat(map).isNotNull() .containsEntry("ToUserName", "gh_4d00ed8d6399") .containsEntry("FromUserName", "oV5CrjpxgaGXNHIQigzNlgLTnwic") .containsEntry("CreateTime", "1481013459") .containsEntry("MsgType", "event"); Map<String, Object> publishEventInfo = (Map<String, Object>) map.get("PublishEventInfo"); assertThat(publishEventInfo).containsEntry("publish_id", "2247503051") .containsEntry("publish_status", "0") .containsEntry("article_id", "b5O2OUs25HBxRceL7hfReg-U9QGeq9zQjiDvy WP4Hq4"); Map<String, Object> articleDetail = (Map<String, Object>) publishEventInfo.get("article_detail"); assertThat(articleDetail).containsEntry("count", "1"); List< Map<String, Object>> item = (List<Map<String, Object>>) articleDetail.get("item"); assertThat(item.get(0)).containsEntry("idx", "1") .containsEntry("article_url", "ARTICLE_URL"); assertThat(item.get(1)).containsEntry("idx", "2") .containsEntry("article_url", "ARTICLE_URL_2"); } }
java
Apache-2.0
84b5c4d2d0774f800237634e5d0336f53c004fe3
2026-01-04T14:46:39.499027Z
false
binarywang/WxJava
https://github.com/binarywang/WxJava/blob/84b5c4d2d0774f800237634e5d0336f53c004fe3/weixin-java-common/src/test/java/me/chanjar/weixin/common/util/DataUtilsTest.java
weixin-java-common/src/test/java/me/chanjar/weixin/common/util/DataUtilsTest.java
package me.chanjar.weixin.common.util; import org.testng.annotations.*; import static org.testng.Assert.*; /** * <pre> * Created by BinaryWang on 2018/5/8. * </pre> * * @author <a href="https://github.com/binarywang">Binary Wang</a> */ public class DataUtilsTest { @Test public void testHandleDataWithSecret() { String data = "js_code=001tZveq0SMoiq1AEXeq0ECJeq0tZveZ&secret=5681022fa1643845392367ea88888888&grant_type=authorization_code&appid=wxe156d4848d999999"; final String s = DataUtils.handleDataWithSecret(data); assertTrue(s.contains("&secret=******&")); } }
java
Apache-2.0
84b5c4d2d0774f800237634e5d0336f53c004fe3
2026-01-04T14:46:39.499027Z
false
binarywang/WxJava
https://github.com/binarywang/WxJava/blob/84b5c4d2d0774f800237634e5d0336f53c004fe3/weixin-java-common/src/test/java/me/chanjar/weixin/common/util/locks/RedisTemplateSimpleDistributedLockSerializationTest.java
weixin-java-common/src/test/java/me/chanjar/weixin/common/util/locks/RedisTemplateSimpleDistributedLockSerializationTest.java
package me.chanjar.weixin.common.util.locks; import org.springframework.data.redis.connection.jedis.JedisConnectionFactory; import org.springframework.data.redis.core.StringRedisTemplate; import org.springframework.data.redis.serializer.StringRedisSerializer; import org.testng.annotations.BeforeTest; import org.testng.annotations.Test; import static org.testng.Assert.*; /** * 测试 RedisTemplateSimpleDistributedLock 在自定义 Key 序列化时的兼容性 * * 这个测试验证修复后的实现确保 tryLock 和 unlock 使用一致的键序列化方式 */ @Test(enabled = false) // 默认禁用,需要Redis实例才能运行 public class RedisTemplateSimpleDistributedLockSerializationTest { private RedisTemplateSimpleDistributedLock redisLock; private StringRedisTemplate redisTemplate; @BeforeTest public void init() { JedisConnectionFactory connectionFactory = new JedisConnectionFactory(); connectionFactory.setHostName("127.0.0.1"); connectionFactory.setPort(6379); connectionFactory.afterPropertiesSet(); // 创建一个带自定义键序列化的 StringRedisTemplate StringRedisTemplate redisTemplate = new StringRedisTemplate(connectionFactory); // 使用自定义键序列化器,模拟在键前面添加前缀的场景 redisTemplate.setKeySerializer(new StringRedisSerializer() { @Override public byte[] serialize(String string) { if (string == null) return null; // 添加 "System:" 前缀,模拟用户自定义的键序列化 return super.serialize("System:" + string); } @Override public String deserialize(byte[] bytes) { if (bytes == null) return null; String result = super.deserialize(bytes); // 移除前缀进行反序列化 return result != null && result.startsWith("System:") ? result.substring(7) : result; } }); this.redisTemplate = redisTemplate; this.redisLock = new RedisTemplateSimpleDistributedLock(redisTemplate, "test_lock_key", 60000); } @Test(description = "测试自定义键序列化器下的锁操作一致性") public void testLockConsistencyWithCustomKeySerializer() { // 1. 获取锁应该成功 assertTrue(redisLock.tryLock(), "第一次获取锁应该成功"); assertNotNull(redisLock.getLockSecretValue(), "锁值应该存在"); // 2. 验证键已正确存储(通过 redisTemplate 直接查询) String actualValue = redisTemplate.opsForValue().get("test_lock_key"); assertEquals(actualValue, redisLock.getLockSecretValue(), "通过 redisTemplate 查询的值应该与锁值相同"); // 3. 再次尝试获取同一把锁应该成功(可重入) assertTrue(redisLock.tryLock(), "可重入锁应该再次获取成功"); // 4. 释放锁应该成功 redisLock.unlock(); assertNull(redisLock.getLockSecretValue(), "释放锁后锁值应该为空"); // 5. 验证键已被删除 actualValue = redisTemplate.opsForValue().get("test_lock_key"); assertNull(actualValue, "释放锁后 Redis 中的键应该被删除"); // 6. 释放已释放的锁应该是安全的 redisLock.unlock(); // 不应该抛出异常 } @Test(description = "测试不同线程使用相同键的锁排他性") public void testLockExclusivityWithCustomKeySerializer() throws InterruptedException { // 第一个锁实例获取锁 assertTrue(redisLock.tryLock(), "第一个锁实例应该成功获取锁"); // 创建第二个锁实例使用相同的键 RedisTemplateSimpleDistributedLock anotherLock = new RedisTemplateSimpleDistributedLock( redisTemplate, "test_lock_key", 60000); // 第二个锁实例不应该能获取锁 assertFalse(anotherLock.tryLock(), "第二个锁实例不应该能获取已被占用的锁"); // 释放第一个锁 redisLock.unlock(); // 现在第二个锁实例应该能获取锁 assertTrue(anotherLock.tryLock(), "第一个锁释放后,第二个锁实例应该能获取锁"); // 清理 anotherLock.unlock(); } }
java
Apache-2.0
84b5c4d2d0774f800237634e5d0336f53c004fe3
2026-01-04T14:46:39.499027Z
false
binarywang/WxJava
https://github.com/binarywang/WxJava/blob/84b5c4d2d0774f800237634e5d0336f53c004fe3/weixin-java-common/src/test/java/me/chanjar/weixin/common/util/locks/RedisTemplateSimpleDistributedLockTest.java
weixin-java-common/src/test/java/me/chanjar/weixin/common/util/locks/RedisTemplateSimpleDistributedLockTest.java
package me.chanjar.weixin.common.util.locks; import lombok.extern.slf4j.Slf4j; import org.jetbrains.annotations.NotNull; import org.springframework.data.redis.connection.jedis.JedisConnectionFactory; import org.springframework.data.redis.core.StringRedisTemplate; import org.springframework.data.redis.serializer.StringRedisSerializer; import org.testng.annotations.BeforeTest; import org.testng.annotations.Test; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import static org.testng.Assert.*; @Slf4j @Test(enabled = true) public class RedisTemplateSimpleDistributedLockTest { private static final String KEY_PREFIX = "System:"; RedisTemplateSimpleDistributedLock redisLock; StringRedisTemplate redisTemplate; AtomicInteger lockCurrentExecuteCounter; @BeforeTest public void init() { JedisConnectionFactory connectionFactory = new JedisConnectionFactory(); connectionFactory.setHostName("127.0.0.1"); connectionFactory.setPort(6379); connectionFactory.afterPropertiesSet(); StringRedisTemplate redisTemplate = new StringRedisTemplate(connectionFactory); // 自定义序列化器,为 key 自动加前缀 redisTemplate.setKeySerializer(new StringRedisSerializer() { @NotNull @Override public byte[] serialize(String string) { if (string == null) { return super.serialize(null); } // 添加前缀 return super.serialize(KEY_PREFIX + string); } @NotNull @Override public String deserialize(byte[] bytes) { String key = super.deserialize(bytes); if (key.startsWith(KEY_PREFIX)) { return key.substring(KEY_PREFIX.length()); } return key; } }); this.redisTemplate = redisTemplate; this.redisLock = new RedisTemplateSimpleDistributedLock(redisTemplate, 60000); this.lockCurrentExecuteCounter = new AtomicInteger(0); } @Test(description = "多线程测试锁排他性") public void testLockExclusive() throws InterruptedException { int threadSize = 100; final CountDownLatch startLatch = new CountDownLatch(threadSize); final CountDownLatch endLatch = new CountDownLatch(threadSize); for (int i = 0; i < threadSize; i++) { new Thread(() -> { try { startLatch.await(); } catch (InterruptedException e) { log.error("unexpected exception", e); } redisLock.lock(); assertEquals(lockCurrentExecuteCounter.incrementAndGet(), 1, "临界区同时只能有一个线程执行"); lockCurrentExecuteCounter.decrementAndGet(); redisLock.unlock(); endLatch.countDown(); }).start(); startLatch.countDown(); } endLatch.await(); } @Test public void testTryLock() throws InterruptedException { assertTrue(redisLock.tryLock(3, TimeUnit.SECONDS), "第一次加锁应该成功"); assertNotNull(redisLock.getLockSecretValue()); String redisValue = this.redisTemplate.opsForValue().get(redisLock.getKey()); assertEquals(redisValue, redisLock.getLockSecretValue()); redisLock.unlock(); assertNull(redisLock.getLockSecretValue()); redisValue = this.redisTemplate.opsForValue().get(redisLock.getKey()); assertNull(redisValue, "释放锁后key会被删除"); redisLock.unlock(); } }
java
Apache-2.0
84b5c4d2d0774f800237634e5d0336f53c004fe3
2026-01-04T14:46:39.499027Z
false
binarywang/WxJava
https://github.com/binarywang/WxJava/blob/84b5c4d2d0774f800237634e5d0336f53c004fe3/weixin-java-common/src/test/java/me/chanjar/weixin/common/util/json/GsonHelperTest.java
weixin-java-common/src/test/java/me/chanjar/weixin/common/util/json/GsonHelperTest.java
package me.chanjar.weixin.common.util.json; import com.google.gson.JsonObject; import org.testng.annotations.Test; import static org.assertj.core.api.Assertions.assertThat; /** * GsonHelper 的单元测试. * * @author <a href="https://github.com/binarywang">Binary Wang</a> * created on 2020-09-04 */ public class GsonHelperTest { @Test public void testIsNull() { } @Test public void testIsNotNull() { } @Test public void testGetLong() { } @Test public void testGetPrimitiveLong() { } @Test public void testGetInteger() { } @Test public void testGetPrimitiveInteger() { } @Test public void testGetDouble() { } @Test public void testGetPrimitiveDouble() { } @Test public void testGetFloat() { } @Test public void testGetPrimitiveFloat() { } @Test public void testGetBoolean() { } @Test public void testGetString() { } @Test public void testGetAsString() { } @Test public void testGetAsLong() { } @Test public void testGetAsPrimitiveLong() { } @Test public void testGetAsInteger() { } @Test public void testGetAsPrimitiveInt() { } @Test public void testGetAsBoolean() { } @Test public void testGetAsPrimitiveBool() { } @Test public void testGetAsDouble() { } @Test public void testGetAsPrimitiveDouble() { } @Test public void testGetAsFloat() { } @Test public void testGetAsPrimitiveFloat() { } @Test public void testGetIntArray() { } @Test public void testGetStringArray() { } @Test public void testGetLongArray() { } @Test public void testGetAsJsonArray() { } @Test public void testBuildSimpleJsonObject() { try { GsonHelper.buildJsonObject(1, 2, 3); } catch (RuntimeException e) { assertThat(e.getMessage()).isEqualTo("参数个数必须为偶数"); } System.out.println(GsonHelper.buildJsonObject(1, 2)); System.out.println(GsonHelper.buildJsonObject(1, null)); System.out.println(GsonHelper.buildJsonObject("int", 1, "float", 2.1f, "double", 2.5)); System.out.println(GsonHelper.buildJsonObject("boolean", true, "string", "1av")); System.out.println(GsonHelper.buildJsonObject(1, true, "jsonElement", new JsonObject())); System.out.println(GsonHelper.buildJsonObject("num", 2, "string", "cde", "char", 'a', "bool", true)); } }
java
Apache-2.0
84b5c4d2d0774f800237634e5d0336f53c004fe3
2026-01-04T14:46:39.499027Z
false
binarywang/WxJava
https://github.com/binarywang/WxJava/blob/84b5c4d2d0774f800237634e5d0336f53c004fe3/weixin-java-common/src/test/java/me/chanjar/weixin/common/util/json/GsonParserTest.java
weixin-java-common/src/test/java/me/chanjar/weixin/common/util/json/GsonParserTest.java
package me.chanjar.weixin.common.util.json; import com.google.gson.JsonObject; import com.google.gson.stream.JsonReader; import org.testng.annotations.Test; import java.io.StringReader; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertNotNull; /** * GsonParser 测试类 * * @author <a href="https://github.com/binarywang">Binary Wang</a> */ public class GsonParserTest { @Test public void testParseString() { String json = "{\"code\":\"ALREADY_EXISTS\",\"message\":\"当前订单已关闭,可查询订单了解关闭原因\"}"; JsonObject jsonObject = GsonParser.parse(json); assertNotNull(jsonObject); assertEquals(jsonObject.get("code").getAsString(), "ALREADY_EXISTS"); assertEquals(jsonObject.get("message").getAsString(), "当前订单已关闭,可查询订单了解关闭原因"); } @Test public void testParseReader() { String json = "{\"code\":\"SUCCESS\",\"message\":\"处理成功\"}"; StringReader reader = new StringReader(json); JsonObject jsonObject = GsonParser.parse(reader); assertNotNull(jsonObject); assertEquals(jsonObject.get("code").getAsString(), "SUCCESS"); assertEquals(jsonObject.get("message").getAsString(), "处理成功"); } @Test public void testParseJsonReader() { String json = "{\"errcode\":0,\"errmsg\":\"ok\"}"; JsonReader jsonReader = new JsonReader(new StringReader(json)); JsonObject jsonObject = GsonParser.parse(jsonReader); assertNotNull(jsonObject); assertEquals(jsonObject.get("errcode").getAsInt(), 0); assertEquals(jsonObject.get("errmsg").getAsString(), "ok"); } }
java
Apache-2.0
84b5c4d2d0774f800237634e5d0336f53c004fe3
2026-01-04T14:46:39.499027Z
false
binarywang/WxJava
https://github.com/binarywang/WxJava/blob/84b5c4d2d0774f800237634e5d0336f53c004fe3/weixin-java-common/src/test/java/me/chanjar/weixin/common/util/crypto/WxCryptUtilTest.java
weixin-java-common/src/test/java/me/chanjar/weixin/common/util/crypto/WxCryptUtilTest.java
package me.chanjar.weixin.common.util.crypto; import java.io.IOException; import java.io.StringReader; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import org.testng.annotations.*; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NodeList; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import static org.testng.Assert.*; @Test public class WxCryptUtilTest { String encodingAesKey = "abcdefghijklmnopqrstuvwxyz0123456789ABCDEFG"; String token = "pamtest"; String timestamp = "1409304348"; String nonce = "xxxxxx"; String appId = "wxb11529c136998cb6"; String randomStr = "aaaabbbbccccdddd"; String xmlFormat = "<xml><ToUserName><![CDATA[toUser]]></ToUserName><Encrypt><![CDATA[%1$s]]></Encrypt></xml>"; String replyMsg = "我是中文abcd123"; String afterAesEncrypt = "jn1L23DB+6ELqJ+6bruv21Y6MD7KeIfP82D6gU39rmkgczbWwt5+3bnyg5K55bgVtVzd832WzZGMhkP72vVOfg=="; String replyMsg2 = "<xml><ToUserName><![CDATA[oia2Tj我是中文jewbmiOUlr6X-1crbLOvLw]]></ToUserName><FromUserName><![CDATA[gh_7f083739789a]]></FromUserName><CreateTime>1407743423</CreateTime><MsgType><![CDATA[video]]></MsgType><Video><MediaId><![CDATA[eYJ1MbwPRJtOvIEabaxHs7TX2D-HV71s79GUxqdUkjm6Gs2Ed1KF3ulAOA9H1xG0]]></MediaId><Title><![CDATA[testCallBackReplyVideo]]></Title><Description><![CDATA[testCallBackReplyVideo]]></Description></Video></xml>"; String afterAesEncrypt2 = "jn1L23DB+6ELqJ+6bruv23M2GmYfkv0xBh2h+XTBOKVKcgDFHle6gqcZ1cZrk3e1qjPQ1F4RsLWzQRG9udbKWesxlkupqcEcW7ZQweImX9+wLMa0GaUzpkycA8+IamDBxn5loLgZpnS7fVAbExOkK5DYHBmv5tptA9tklE/fTIILHR8HLXa5nQvFb3tYPKAlHF3rtTeayNf0QuM+UW/wM9enGIDIJHF7CLHiDNAYxr+r+OrJCmPQyTy8cVWlu9iSvOHPT/77bZqJucQHQ04sq7KZI27OcqpQNSto2OdHCoTccjggX5Z9Mma0nMJBU+jLKJ38YB1fBIz+vBzsYjrTmFQ44YfeEuZ+xRTQwr92vhA9OxchWVINGC50qE/6lmkwWTwGX9wtQpsJKhP+oS7rvTY8+VdzETdfakjkwQ5/Xka042OlUb1/slTwo4RscuQ+RdxSGvDahxAJ6+EAjLt9d8igHngxIbf6YyqqROxuxqIeIch3CssH/LqRs+iAcILvApYZckqmA7FNERspKA5f8GoJ9sv8xmGvZ9Yrf57cExWtnX8aCMMaBropU/1k+hKP5LVdzbWCG0hGwx/dQudYR/eXp3P0XxjlFiy+9DMlaFExWUZQDajPkdPrEeOwofJb"; public void testNormal() throws ParserConfigurationException, SAXException, IOException { WxCryptUtil pc = new WxCryptUtil(this.token, this.encodingAesKey, this.appId); String encryptedXml = pc.encrypt(this.replyMsg); System.out.println(encryptedXml); DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); documentBuilderFactory.setExpandEntityReferences(false); documentBuilderFactory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true); DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); Document document = documentBuilder.parse(new InputSource(new StringReader(encryptedXml))); Element root = document.getDocumentElement(); String cipherText = root.getElementsByTagName("Encrypt").item(0).getTextContent(); System.out.println(cipherText); String msgSignature = root.getElementsByTagName("MsgSignature").item(0).getTextContent(); System.out.println(msgSignature); String timestamp = root.getElementsByTagName("TimeStamp").item(0).getTextContent(); System.out.println(timestamp); String nonce = root.getElementsByTagName("Nonce").item(0).getTextContent(); System.out.println(nonce); String messageText = String.format(this.xmlFormat, cipherText); System.out.println(messageText); // 第三方收到企业号平台发送的消息 String plainMessage = pc.decrypt(cipherText); System.out.println(plainMessage); assertEquals(plainMessage, this.replyMsg); } public void testAesEncrypt() { WxCryptUtil pc = new WxCryptUtil(this.token, this.encodingAesKey, this.appId); assertEquals(pc.encrypt(this.randomStr, this.replyMsg), this.afterAesEncrypt); } public void testAesEncrypt2() { WxCryptUtil pc = new WxCryptUtil(this.token, this.encodingAesKey, this.appId); assertEquals(pc.encrypt(this.randomStr, this.replyMsg2), this.afterAesEncrypt2); } public void testValidateSignatureError() throws ParserConfigurationException, SAXException, IOException { try { WxCryptUtil pc = new WxCryptUtil(this.token, this.encodingAesKey, this.appId); String afterEncrpt = pc.encrypt(this.replyMsg); DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setExpandEntityReferences(false); dbf.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true); DocumentBuilder db = dbf.newDocumentBuilder(); StringReader sr = new StringReader(afterEncrpt); InputSource is = new InputSource(sr); Document document = db.parse(is); Element root = document.getDocumentElement(); NodeList nodelist1 = root.getElementsByTagName("Encrypt"); String encrypt = nodelist1.item(0).getTextContent(); String fromXML = String.format(this.xmlFormat, encrypt); pc.decryptXml("12345", this.timestamp, this.nonce, fromXML); // 这里签名错误 } catch (RuntimeException e) { assertEquals(e.getMessage(), "加密消息签名校验失败"); return; } fail("错误流程不抛出异常???"); } }
java
Apache-2.0
84b5c4d2d0774f800237634e5d0336f53c004fe3
2026-01-04T14:46:39.499027Z
false
binarywang/WxJava
https://github.com/binarywang/WxJava/blob/84b5c4d2d0774f800237634e5d0336f53c004fe3/weixin-java-common/src/test/java/me/chanjar/weixin/common/util/crypto/SHA1Test.java
weixin-java-common/src/test/java/me/chanjar/weixin/common/util/crypto/SHA1Test.java
package me.chanjar.weixin.common.util.crypto; import org.testng.annotations.Test; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertNotNull; /** * <pre> * Created by BinaryWang on 2017/6/10. * </pre> * * @author <a href="https://github.com/binarywang">Binary Wang</a> */ public class SHA1Test { @Test public void testGen() throws Exception { final String result = SHA1.gen("123", "345"); assertNotNull(result); assertEquals(result,"9f537aeb751ec72605f57f94a2f6dc3e3958e1dd"); } @Test(expectedExceptions = {IllegalArgumentException.class}) public void testGen_illegalArguments() { final String result = SHA1.gen(null, "", "345"); assertNotNull(result); } @Test public void testGenWithAmple() throws Exception { final String result = SHA1.genWithAmple("123", "345"); assertNotNull(result); assertEquals(result,"20b896ccbd5a72dde5dbe0878ff985e4069771c6"); } }
java
Apache-2.0
84b5c4d2d0774f800237634e5d0336f53c004fe3
2026-01-04T14:46:39.499027Z
false
binarywang/WxJava
https://github.com/binarywang/WxJava/blob/84b5c4d2d0774f800237634e5d0336f53c004fe3/weixin-java-common/src/test/java/me/chanjar/weixin/common/util/fs/FileUtilsTest.java
weixin-java-common/src/test/java/me/chanjar/weixin/common/util/fs/FileUtilsTest.java
package me.chanjar.weixin.common.util.fs; import org.apache.commons.io.IOUtils; import org.testng.annotations.Test; import java.io.ByteArrayInputStream; import java.io.File; import java.io.IOException; import java.nio.charset.Charset; import java.nio.file.Files; import java.util.List; import static org.assertj.core.api.Assertions.assertThat; public class FileUtilsTest { @Test public void testCreateTmpFile() throws IOException { String strings = "abc"; File tmpFile = FileUtils.createTmpFile(new ByteArrayInputStream(strings.getBytes()), "name", "txt"); System.out.println(tmpFile); List<String> lines = IOUtils.readLines(Files.newInputStream(tmpFile.toPath()), Charset.defaultCharset()); assertThat(lines).hasSize(1); assertThat(lines.get(0)).isEqualTo(strings); } @Test public void testTestCreateTmpFile() { } @Test public void testImageToBase64ByStream() { } }
java
Apache-2.0
84b5c4d2d0774f800237634e5d0336f53c004fe3
2026-01-04T14:46:39.499027Z
false
binarywang/WxJava
https://github.com/binarywang/WxJava/blob/84b5c4d2d0774f800237634e5d0336f53c004fe3/weixin-java-common/src/test/java/me/chanjar/weixin/common/util/http/HttpResponseProxyTest.java
weixin-java-common/src/test/java/me/chanjar/weixin/common/util/http/HttpResponseProxyTest.java
package me.chanjar.weixin.common.util.http; import me.chanjar.weixin.common.error.WxErrorException; import me.chanjar.weixin.common.util.http.apache.ApacheHttpResponseProxy; import org.testng.annotations.Test; import static org.testng.Assert.*; public class HttpResponseProxyTest { @Test public void testExtractFileNameFromContentString() throws WxErrorException { String content = "attachment; filename*=utf-8''%E6%B5%8B%E8%AF%95.xlsx; filename=\"æµ�è¯�.xlsx\""; String filename = HttpResponseProxy.extractFileNameFromContentString(content); assertNotNull(filename); assertEquals(filename, "测试.xlsx"); } @Test public void testExtractFileNameFromContentString_another() throws WxErrorException { String content = "attachment; filename*=utf-8''%E8%90%A5%E4%B8%9A%E6%89%A7%E7%85%A7.jpg; filename=\"è�¥ä¸�æ�§ç�§.jpg\""; // String content = "attachment; filename=\"è�¥ä¸�æ�§ç�§.jpg\""; String filename = HttpResponseProxy.extractFileNameFromContentString(content); assertNotNull(filename); assertEquals(filename, "营业执照.jpg"); } }
java
Apache-2.0
84b5c4d2d0774f800237634e5d0336f53c004fe3
2026-01-04T14:46:39.499027Z
false
binarywang/WxJava
https://github.com/binarywang/WxJava/blob/84b5c4d2d0774f800237634e5d0336f53c004fe3/weixin-java-common/src/test/java/me/chanjar/weixin/common/util/http/apache/SSLConfigurationTest.java
weixin-java-common/src/test/java/me/chanjar/weixin/common/util/http/apache/SSLConfigurationTest.java
package me.chanjar.weixin.common.util.http.apache; import org.apache.http.conn.ssl.SSLConnectionSocketFactory; import org.apache.http.impl.client.CloseableHttpClient; import org.testng.Assert; import org.testng.annotations.Test; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLSocket; import javax.net.ssl.SSLSocketFactory; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.util.Arrays; import java.util.List; /** * 测试SSL配置,特别是TLS协议版本配置 * Test SSL configuration, especially TLS protocol version configuration */ public class SSLConfigurationTest { @Test public void testDefaultTLSProtocols() throws Exception { // Create a new instance to check the default configuration Class<?> builderClass = DefaultApacheHttpClientBuilder.class; Object builder = builderClass.getDeclaredMethod("get").invoke(null); // 验证默认支持的TLS协议版本包含现代版本 Field supportedProtocolsField = builderClass.getDeclaredField("supportedProtocols"); supportedProtocolsField.setAccessible(true); String[] supportedProtocols = (String[]) supportedProtocolsField.get(builder); List<String> protocolList = Arrays.asList(supportedProtocols); System.out.println("Default supported TLS protocols: " + Arrays.toString(supportedProtocols)); // 主要验证:应该支持TLS 1.2和/或1.3 (现代安全版本) // Main validation: Should support TLS 1.2 and/or 1.3 (modern secure versions) Assert.assertTrue(protocolList.contains("TLSv1.2"), "Should support TLS 1.2"); Assert.assertTrue(protocolList.contains("TLSv1.3"), "Should support TLS 1.3"); // 验证不再是只有TLS 1.0 (这是导致原问题的根本原因) // Verify it's no longer just TLS 1.0 (which was the root cause of the original issue) Assert.assertTrue(protocolList.size() > 0, "Should support at least one TLS version"); boolean hasModernTLS = protocolList.contains("TLSv1.2") || protocolList.contains("TLSv1.3"); Assert.assertTrue(hasModernTLS, "Should support at least one modern TLS version (1.2 or 1.3)"); // 验证不是原来的老旧配置 (只有 "TLSv1") // Verify it's not the old configuration (only "TLSv1") boolean isOldConfig = protocolList.size() == 1 && protocolList.contains("TLSv1"); Assert.assertFalse(isOldConfig, "Should not be the old configuration that only supported TLS 1.0"); } @Test public void testCustomTLSProtocols() throws Exception { // Test that we can set custom TLS protocols String[] customProtocols = {"TLSv1.2", "TLSv1.3"}; // Create a new builder instance using reflection to avoid singleton issues in testing Class<?> builderClass = DefaultApacheHttpClientBuilder.class; Constructor<?> constructor = builderClass.getDeclaredConstructor(); constructor.setAccessible(true); Object builder = constructor.newInstance(); // Set custom protocols builderClass.getMethod("supportedProtocols", String[].class).invoke(builder, (Object) customProtocols); Field supportedProtocolsField = builderClass.getDeclaredField("supportedProtocols"); supportedProtocolsField.setAccessible(true); String[] actualProtocols = (String[]) supportedProtocolsField.get(builder); Assert.assertEquals(actualProtocols, customProtocols, "Custom protocols should be set correctly"); System.out.println("Custom supported TLS protocols: " + Arrays.toString(actualProtocols)); } @Test public void testSSLContextCreation() throws Exception { DefaultApacheHttpClientBuilder builder = DefaultApacheHttpClientBuilder.get(); // 构建HTTP客户端以验证SSL工厂是否正确创建 CloseableHttpClient client = builder.build(); Assert.assertNotNull(client, "HTTP client should be created successfully"); // 验证SSL上下文支持现代TLS协议 SSLContext sslContext = SSLContext.getDefault(); SSLSocketFactory socketFactory = sslContext.getSocketFactory(); // 创建一个SSL socket来检查支持的协议 try (SSLSocket socket = (SSLSocket) socketFactory.createSocket()) { String[] supportedProtocols = socket.getSupportedProtocols(); List<String> supportedList = Arrays.asList(supportedProtocols); // JVM应该支持TLS 1.2(在JDK 8+中默认可用) Assert.assertTrue(supportedList.contains("TLSv1.2"), "JVM should support TLS 1.2. Supported protocols: " + Arrays.toString(supportedProtocols)); System.out.println("JVM supported TLS protocols: " + Arrays.toString(supportedProtocols)); } client.close(); } @Test public void testBuilderChaining() { DefaultApacheHttpClientBuilder builder = DefaultApacheHttpClientBuilder.get(); // 测试方法链调用 ApacheHttpClientBuilder result = builder .supportedProtocols(new String[]{"TLSv1.2", "TLSv1.3"}) .httpProxyHost("proxy.example.com") .httpProxyPort(8080); Assert.assertSame(result, builder, "Builder methods should return the same instance for method chaining"); } }
java
Apache-2.0
84b5c4d2d0774f800237634e5d0336f53c004fe3
2026-01-04T14:46:39.499027Z
false
binarywang/WxJava
https://github.com/binarywang/WxJava/blob/84b5c4d2d0774f800237634e5d0336f53c004fe3/weixin-java-common/src/test/java/me/chanjar/weixin/common/util/http/apache/SSLIntegrationTest.java
weixin-java-common/src/test/java/me/chanjar/weixin/common/util/http/apache/SSLIntegrationTest.java
package me.chanjar.weixin.common.util.http.apache; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.CloseableHttpClient; import org.testng.Assert; import org.testng.annotations.Test; /** * 集成测试 - 验证SSL配置可以正常访问HTTPS网站 * Integration test - Verify SSL configuration can access HTTPS websites properly */ public class SSLIntegrationTest { @Test public void testHTTPSConnectionWithModernTLS() throws Exception { DefaultApacheHttpClientBuilder builder = DefaultApacheHttpClientBuilder.get(); // 使用默认配置(支持现代TLS版本)创建客户端 CloseableHttpClient client = builder.build(); // 测试访问一个需要现代TLS的网站 // Test accessing a website that requires modern TLS HttpGet httpGet = new HttpGet("https://api.weixin.qq.com/"); try (CloseableHttpResponse response = client.execute(httpGet)) { // 验证能够成功建立HTTPS连接(不管响应内容是什么) // Verify that HTTPS connection can be established successfully (regardless of response content) Assert.assertNotNull(response, "Should be able to establish HTTPS connection"); Assert.assertNotNull(response.getStatusLine(), "Should receive a status response"); int statusCode = response.getStatusLine().getStatusCode(); // 任何HTTP状态码都表示SSL握手成功 // Any HTTP status code indicates successful SSL handshake Assert.assertTrue(statusCode > 0, "Should receive a valid HTTP status code, got: " + statusCode); System.out.println("HTTPS connection test successful. Status: " + response.getStatusLine()); } catch (javax.net.ssl.SSLHandshakeException e) { Assert.fail("SSL handshake should not fail with modern TLS configuration. Error: " + e.getMessage()); } finally { client.close(); } } @Test public void testCustomTLSConfiguration() throws Exception { DefaultApacheHttpClientBuilder builder = DefaultApacheHttpClientBuilder.get(); // 配置为只支持TLS 1.2和1.3(最安全的配置) // Configure to only support TLS 1.2 and 1.3 (most secure configuration) builder.supportedProtocols(new String[]{"TLSv1.2", "TLSv1.3"}); CloseableHttpClient client = builder.build(); // 测试这个配置是否能正常工作 HttpGet httpGet = new HttpGet("https://httpbin.org/get"); try (CloseableHttpResponse response = client.execute(httpGet)) { Assert.assertNotNull(response, "Should be able to establish HTTPS connection with TLS 1.2/1.3"); int statusCode = response.getStatusLine().getStatusCode(); Assert.assertEquals(statusCode, 200, "Should get HTTP 200 response from httpbin.org"); System.out.println("Custom TLS configuration test successful. Status: " + response.getStatusLine()); } catch (javax.net.ssl.SSLHandshakeException e) { // 这个测试可能会因为网络环境而失败,所以我们只是记录警告 // This test might fail due to network environment, so we just log a warning System.out.println("Warning: SSL handshake failed with custom TLS config: " + e.getMessage()); System.out.println("This might be due to network restrictions in the test environment."); } finally { client.close(); } } }
java
Apache-2.0
84b5c4d2d0774f800237634e5d0336f53c004fe3
2026-01-04T14:46:39.499027Z
false
binarywang/WxJava
https://github.com/binarywang/WxJava/blob/84b5c4d2d0774f800237634e5d0336f53c004fe3/weixin-java-common/src/test/java/me/chanjar/weixin/common/util/http/apache/DefaultApacheHttpClientBuilderTest.java
weixin-java-common/src/test/java/me/chanjar/weixin/common/util/http/apache/DefaultApacheHttpClientBuilderTest.java
package me.chanjar.weixin.common.util.http.apache; import org.apache.http.HttpRequestInterceptor; import org.apache.http.HttpResponseInterceptor; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpUriRequest; import org.apache.http.client.protocol.HttpClientContext; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.protocol.BasicHttpContext; import org.apache.http.protocol.HttpContext; import org.apache.http.protocol.HttpCoreContext; import org.testng.Assert; import org.testng.annotations.Test; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; import java.util.stream.Stream; public class DefaultApacheHttpClientBuilderTest { @Test public void testBuild() throws Exception { DefaultApacheHttpClientBuilder builder1 = DefaultApacheHttpClientBuilder.get(); DefaultApacheHttpClientBuilder builder2 = DefaultApacheHttpClientBuilder.get(); Assert.assertSame(builder1, builder2, "DefaultApacheHttpClientBuilder为单例,获取到的对象应该相同"); List<TestThread> threadList = new ArrayList<>(10); for (int i = 0; i < 10; i++) { TestThread thread = new TestThread(); thread.start(); threadList.add(thread); } for (TestThread testThread : threadList) { testThread.join(); Assert.assertNotEquals(-1, testThread.getRespState(), "请求响应code不应为-1"); } for (int i = 1; i < threadList.size(); i++) { TestThread thread1 = threadList.get(i - 1); TestThread thread2 = threadList.get(i); Assert.assertSame( thread1.getClient(), thread2.getClient(), "DefaultApacheHttpClientBuilder为单例,并持有了相同的HttpClient" ); } } @Test void testHttpClientWithInterceptor() throws Exception { DefaultApacheHttpClientBuilder builder = DefaultApacheHttpClientBuilder.get(); List<String> interceptorOrder = new ArrayList<>(); HttpRequestInterceptor requestInterceptor1 = (request, context) -> { context.setAttribute("interceptor_called", "requestInterceptor1"); interceptorOrder.add("requestInterceptor1"); }; HttpRequestInterceptor requestInterceptor2 = (request, context) -> { interceptorOrder.add("requestInterceptor2"); }; HttpResponseInterceptor responseInterceptor1 = (response, context) -> { interceptorOrder.add("responseInterceptor1"); }; HttpResponseInterceptor responseInterceptor2 = (response, context) -> { interceptorOrder.add("responseInterceptor2"); }; builder.setRequestInterceptors(Stream.of(requestInterceptor1, requestInterceptor2).collect(Collectors.toList())); builder.setResponseInterceptors(Stream.of(responseInterceptor1, responseInterceptor2).collect(Collectors.toList())); try (CloseableHttpClient client = builder.build()) { HttpUriRequest request = new HttpGet("http://localhost:8080"); HttpContext context = HttpClientContext.create(); try (CloseableHttpResponse resp = client.execute(request, context)) { Assert.assertEquals(context.getAttribute("interceptor_called"), "requestInterceptor1", "成功调用 requestInterceptor1 并向 content 中写入了数据"); // 测试拦截器执行顺序 Assert.assertEquals(interceptorOrder.get(0), "requestInterceptor1"); Assert.assertEquals(interceptorOrder.get(1), "requestInterceptor2"); Assert.assertEquals(interceptorOrder.get(2), "responseInterceptor1"); Assert.assertEquals(interceptorOrder.get(3), "responseInterceptor2"); } } } public static class TestThread extends Thread { private CloseableHttpClient client; private int respState = -1; @Override public void run() { client = DefaultApacheHttpClientBuilder.get().build(); HttpGet httpGet = new HttpGet("http://www.sina.com.cn/"); try (CloseableHttpResponse resp = client.execute(httpGet)) { respState = resp.getStatusLine().getStatusCode(); } catch (IOException ignored) { } } public CloseableHttpClient getClient() { return client; } public int getRespState() { return respState; } } }
java
Apache-2.0
84b5c4d2d0774f800237634e5d0336f53c004fe3
2026-01-04T14:46:39.499027Z
false
binarywang/WxJava
https://github.com/binarywang/WxJava/blob/84b5c4d2d0774f800237634e5d0336f53c004fe3/weixin-java-common/src/test/java/me/chanjar/weixin/common/util/http/okhttp/DefaultOkHttpClientBuilderTest.java
weixin-java-common/src/test/java/me/chanjar/weixin/common/util/http/okhttp/DefaultOkHttpClientBuilderTest.java
package me.chanjar.weixin.common.util.http.okhttp; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.Response; import org.testng.Assert; import org.testng.annotations.Test; import java.io.IOException; import java.util.ArrayList; import java.util.List; public class DefaultOkHttpClientBuilderTest { @Test public void testBuild() throws Exception { DefaultOkHttpClientBuilder builder1 = DefaultOkHttpClientBuilder.get(); DefaultOkHttpClientBuilder builder2 = DefaultOkHttpClientBuilder.get(); Assert.assertSame(builder1, builder2, "DefaultOkHttpClientBuilder为单例,获取到的对象应该相同"); List<DefaultOkHttpClientBuilderTest.TestThread> threadList = new ArrayList<>(10); for (int i = 0; i < 10; i++) { DefaultOkHttpClientBuilderTest.TestThread thread = new DefaultOkHttpClientBuilderTest.TestThread(); thread.start(); threadList.add(thread); } for (DefaultOkHttpClientBuilderTest.TestThread testThread : threadList) { testThread.join(); Assert.assertNotEquals(-1, testThread.getRespState(), "请求响应code不应为-1"); } for (int i = 1; i < threadList.size(); i++) { DefaultOkHttpClientBuilderTest.TestThread thread1 = threadList.get(i - 1); DefaultOkHttpClientBuilderTest.TestThread thread2 = threadList.get(i); Assert.assertSame( thread1.getClient(), thread2.getClient(), "DefaultOkHttpClientBuilderTest为单例,并持有了相同的OkHttpClient" ); } } public static class TestThread extends Thread { private OkHttpClient client; private int respState = -1; @Override public void run() { client = DefaultOkHttpClientBuilder.get().build(); Request request = new Request.Builder() .url("http://www.sina.com.cn/") .build(); try (Response response = client.newCall(request).execute()) { respState = response.code(); } catch (IOException e) { // ignore } } public OkHttpClient getClient() { return client; } public int getRespState() { return respState; } } }
java
Apache-2.0
84b5c4d2d0774f800237634e5d0336f53c004fe3
2026-01-04T14:46:39.499027Z
false
binarywang/WxJava
https://github.com/binarywang/WxJava/blob/84b5c4d2d0774f800237634e5d0336f53c004fe3/weixin-java-common/src/test/java/me/chanjar/weixin/common/error/WxErrorTest.java
weixin-java-common/src/test/java/me/chanjar/weixin/common/error/WxErrorTest.java
package me.chanjar.weixin.common.error; import me.chanjar.weixin.common.enums.WxType; import org.testng.annotations.Test; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertNull; @Test public class WxErrorTest { public void testFromJson() { String json = "{ \"errcode\": 40003, \"errmsg\": \"invalid openid\" }"; WxError wxError = WxError.fromJson(json, WxType.MP); assertEquals(40003, wxError.getErrorCode()); assertEquals(wxError.getErrorMsgEn(), "invalid openid"); } public void testFromBadJson1() { String json = "{ \"errcode\": 40003, \"errmsg\": \"invalid openid\", \"media_id\": \"12323423dsfafsf232f\" }"; WxError wxError = WxError.fromJson(json, WxType.MP); assertEquals(40003, wxError.getErrorCode()); assertEquals(wxError.getErrorMsgEn(), "invalid openid"); } public void testFromBadJson2() { String json = "{\"access_token\":\"ACCESS_TOKEN\",\"expires_in\":7200}"; WxError wxError = WxError.fromJson(json, WxType.MP); assertEquals(0, wxError.getErrorCode()); assertNull(wxError.getErrorMsg()); } }
java
Apache-2.0
84b5c4d2d0774f800237634e5d0336f53c004fe3
2026-01-04T14:46:39.499027Z
false
binarywang/WxJava
https://github.com/binarywang/WxJava/blob/84b5c4d2d0774f800237634e5d0336f53c004fe3/weixin-java-common/src/test/java/me/chanjar/weixin/common/redis/CommonWxRedisOpsTest.java
weixin-java-common/src/test/java/me/chanjar/weixin/common/redis/CommonWxRedisOpsTest.java
package me.chanjar.weixin.common.redis; import org.testng.Assert; import org.testng.annotations.Test; import java.util.concurrent.TimeUnit; public class CommonWxRedisOpsTest { protected WxRedisOps wxRedisOps; private String key = "access_token"; private String value = String.valueOf(System.currentTimeMillis()); @Test public void testGetValue() { wxRedisOps.setValue(key, value, 3, TimeUnit.SECONDS); Assert.assertEquals(wxRedisOps.getValue(key), value); } @Test public void testSetValue() { String key = "access_token", value = String.valueOf(System.currentTimeMillis()); wxRedisOps.setValue(key, value, -1, TimeUnit.SECONDS); wxRedisOps.setValue(key, value, 0, TimeUnit.SECONDS); wxRedisOps.setValue(key, value, 1, TimeUnit.SECONDS); } @Test public void testGetExpire() { String key = "access_token", value = String.valueOf(System.currentTimeMillis()); wxRedisOps.setValue(key, value, -1, TimeUnit.SECONDS); Assert.assertTrue(wxRedisOps.getExpire(key) < 0); wxRedisOps.setValue(key, value, 4, TimeUnit.SECONDS); Long expireSeconds = wxRedisOps.getExpire(key); Assert.assertTrue(expireSeconds <= 4 && expireSeconds >= 0); } @Test public void testExpire() { String key = "access_token", value = String.valueOf(System.currentTimeMillis()); wxRedisOps.setValue(key, value, -1, TimeUnit.SECONDS); wxRedisOps.expire(key, 4, TimeUnit.SECONDS); Long expireSeconds = wxRedisOps.getExpire(key); Assert.assertTrue(expireSeconds <= 4 && expireSeconds >= 0); } @Test public void testGetLock() { Assert.assertNotNull(wxRedisOps.getLock("access_token_lock")); } }
java
Apache-2.0
84b5c4d2d0774f800237634e5d0336f53c004fe3
2026-01-04T14:46:39.499027Z
false
binarywang/WxJava
https://github.com/binarywang/WxJava/blob/84b5c4d2d0774f800237634e5d0336f53c004fe3/weixin-java-common/src/test/java/me/chanjar/weixin/common/redis/RedisTemplateWxRedisOpsTest.java
weixin-java-common/src/test/java/me/chanjar/weixin/common/redis/RedisTemplateWxRedisOpsTest.java
package me.chanjar.weixin.common.redis; import org.springframework.data.redis.connection.jedis.JedisConnectionFactory; import org.springframework.data.redis.core.StringRedisTemplate; import org.testng.annotations.AfterTest; import org.testng.annotations.BeforeTest; public class RedisTemplateWxRedisOpsTest extends CommonWxRedisOpsTest { StringRedisTemplate redisTemplate; @BeforeTest public void init() { JedisConnectionFactory connectionFactory = new JedisConnectionFactory(); connectionFactory.setHostName("127.0.0.1"); connectionFactory.setPort(6379); connectionFactory.afterPropertiesSet(); StringRedisTemplate redisTemplate = new StringRedisTemplate(connectionFactory); this.redisTemplate = redisTemplate; this.wxRedisOps = new RedisTemplateWxRedisOps(this.redisTemplate); } @AfterTest public void destroy() { } }
java
Apache-2.0
84b5c4d2d0774f800237634e5d0336f53c004fe3
2026-01-04T14:46:39.499027Z
false
binarywang/WxJava
https://github.com/binarywang/WxJava/blob/84b5c4d2d0774f800237634e5d0336f53c004fe3/weixin-java-common/src/test/java/me/chanjar/weixin/common/redis/JedisWxRedisOpsTest.java
weixin-java-common/src/test/java/me/chanjar/weixin/common/redis/JedisWxRedisOpsTest.java
package me.chanjar.weixin.common.redis; import org.testng.annotations.AfterTest; import org.testng.annotations.BeforeTest; import redis.clients.jedis.JedisPool; public class JedisWxRedisOpsTest extends CommonWxRedisOpsTest { JedisPool jedisPool; @BeforeTest public void init() { this.jedisPool = new JedisPool("127.0.0.1", 6379); this.wxRedisOps = new JedisWxRedisOps(jedisPool); } @AfterTest public void destroy() { this.jedisPool.close(); } }
java
Apache-2.0
84b5c4d2d0774f800237634e5d0336f53c004fe3
2026-01-04T14:46:39.499027Z
false
binarywang/WxJava
https://github.com/binarywang/WxJava/blob/84b5c4d2d0774f800237634e5d0336f53c004fe3/weixin-java-common/src/test/java/me/chanjar/weixin/common/redis/RedissonWxRedisOpsTest.java
weixin-java-common/src/test/java/me/chanjar/weixin/common/redis/RedissonWxRedisOpsTest.java
package me.chanjar.weixin.common.redis; import org.redisson.Redisson; import org.redisson.api.RedissonClient; import org.redisson.config.Config; import org.redisson.config.TransportMode; import org.testng.annotations.AfterTest; import org.testng.annotations.BeforeTest; public class RedissonWxRedisOpsTest extends CommonWxRedisOpsTest { RedissonClient redissonClient; @BeforeTest public void init() { Config config = new Config(); config.useSingleServer().setAddress("redis://127.0.0.1:6379"); config.setTransportMode(TransportMode.NIO); this.redissonClient = Redisson.create(config); this.wxRedisOps = new RedissonWxRedisOps(this.redissonClient); } @AfterTest public void destroy() { this.redissonClient.shutdown(); } }
java
Apache-2.0
84b5c4d2d0774f800237634e5d0336f53c004fe3
2026-01-04T14:46:39.499027Z
false
binarywang/WxJava
https://github.com/binarywang/WxJava/blob/84b5c4d2d0774f800237634e5d0336f53c004fe3/weixin-java-common/src/test/java/me/chanjar/weixin/common/api/WxMessageInMemoryDuplicateCheckerSingletonTest.java
weixin-java-common/src/test/java/me/chanjar/weixin/common/api/WxMessageInMemoryDuplicateCheckerSingletonTest.java
package me.chanjar.weixin.common.api; import org.testng.annotations.Test; import java.util.concurrent.TimeUnit; import static org.testng.Assert.assertFalse; import static org.testng.Assert.assertTrue; /** * @author jiangby * @version 1.0 * created on 2022/5/26 1:46 */ @Test public class WxMessageInMemoryDuplicateCheckerSingletonTest { private static WxMessageInMemoryDuplicateCheckerSingleton checkerSingleton = WxMessageInMemoryDuplicateCheckerSingleton.getInstance(); public void test() throws InterruptedException { Long[] msgIds = new Long[]{1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L}; // 第一次检查 for (Long msgId : msgIds) { boolean result = checkerSingleton.isDuplicate(String.valueOf(msgId)); assertFalse(result); } // 初始化后1S进行检查 每五秒检查一次,过期时间为15秒,过15秒再检查 TimeUnit.SECONDS.sleep(15); for (Long msgId : msgIds) { boolean result = checkerSingleton.isDuplicate(String.valueOf(msgId)); assertTrue(result); } // 过6秒再检查 TimeUnit.SECONDS.sleep(6); for (Long msgId : msgIds) { boolean result = checkerSingleton.isDuplicate(String.valueOf(msgId)); assertFalse(result); } } }
java
Apache-2.0
84b5c4d2d0774f800237634e5d0336f53c004fe3
2026-01-04T14:46:39.499027Z
false
binarywang/WxJava
https://github.com/binarywang/WxJava/blob/84b5c4d2d0774f800237634e5d0336f53c004fe3/weixin-java-common/src/test/java/me/chanjar/weixin/common/api/WxMessageInMemoryDuplicateCheckerTest.java
weixin-java-common/src/test/java/me/chanjar/weixin/common/api/WxMessageInMemoryDuplicateCheckerTest.java
package me.chanjar.weixin.common.api; import org.testng.annotations.Test; import java.util.concurrent.TimeUnit; import static org.testng.Assert.assertFalse; import static org.testng.Assert.assertTrue; @Test public class WxMessageInMemoryDuplicateCheckerTest { private WxMessageInMemoryDuplicateChecker checker = new WxMessageInMemoryDuplicateChecker(2000L, 1000L); public void test() throws InterruptedException { Long[] msgIds = new Long[]{1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L}; // 第一次检查 for (Long msgId : msgIds) { boolean result = checker.isDuplicate(String.valueOf(msgId)); assertFalse(result); } // 过1秒再检查 TimeUnit.SECONDS.sleep(1); for (Long msgId : msgIds) { boolean result = checker.isDuplicate(String.valueOf(msgId)); assertTrue(result); } // 过1.5秒再检查 TimeUnit.MILLISECONDS.sleep(1500L); for (Long msgId : msgIds) { boolean result = checker.isDuplicate(String.valueOf(msgId)); assertFalse(result); } } }
java
Apache-2.0
84b5c4d2d0774f800237634e5d0336f53c004fe3
2026-01-04T14:46:39.499027Z
false
binarywang/WxJava
https://github.com/binarywang/WxJava/blob/84b5c4d2d0774f800237634e5d0336f53c004fe3/weixin-java-common/src/test/java/me/chanjar/weixin/common/api/WxMessageInRedisDuplicateCheckerTest.java
weixin-java-common/src/test/java/me/chanjar/weixin/common/api/WxMessageInRedisDuplicateCheckerTest.java
package me.chanjar.weixin.common.api; import org.redisson.Redisson; import org.redisson.api.RedissonClient; import org.redisson.config.Config; import org.redisson.config.TransportMode; import org.testng.annotations.BeforeTest; import org.testng.annotations.Test; import java.util.concurrent.TimeUnit; import static org.testng.Assert.assertFalse; import static org.testng.Assert.assertTrue; @Test public class WxMessageInRedisDuplicateCheckerTest { private RedissonClient redissonClient; @BeforeTest public void init() { Config config = new Config(); config.useSingleServer().setAddress("redis://127.0.0.1:6379"); config.setTransportMode(TransportMode.NIO); this.redissonClient = Redisson.create(config); checker = new WxMessageInRedisDuplicateChecker(redissonClient); checker.setExpire(2); } private WxMessageInRedisDuplicateChecker checker; public void test() throws InterruptedException { Long[] msgIds = new Long[]{1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L}; // 第一次检查 for (Long msgId : msgIds) { boolean result = checker.isDuplicate(String.valueOf(msgId)); assertFalse(result); } // 过1秒再检查 TimeUnit.SECONDS.sleep(1); for (Long msgId : msgIds) { boolean result = checker.isDuplicate(String.valueOf(msgId)); assertTrue(result); } // 过1.5秒再检查 TimeUnit.MILLISECONDS.sleep(1500L); for (Long msgId : msgIds) { boolean result = checker.isDuplicate(String.valueOf(msgId)); assertFalse(result); } } }
java
Apache-2.0
84b5c4d2d0774f800237634e5d0336f53c004fe3
2026-01-04T14:46:39.499027Z
false
binarywang/WxJava
https://github.com/binarywang/WxJava/blob/84b5c4d2d0774f800237634e5d0336f53c004fe3/weixin-java-common/src/test/java/me/chanjar/weixin/common/session/SessionTest.java
weixin-java-common/src/test/java/me/chanjar/weixin/common/session/SessionTest.java
package me.chanjar.weixin.common.session; import org.testng.*; import org.testng.annotations.*; @Test public class SessionTest { @DataProvider public Object[][] getSessionManager() { return new Object[][]{ new Object[]{new StandardSessionManager()} }; } @Test(dataProvider = "getSessionManager", expectedExceptions = IllegalStateException.class) public void testInvalidate(WxSessionManager sessionManager) { WxSession session = sessionManager.getSession("abc"); session.invalidate(); session.getAttributeNames(); } @Test(dataProvider = "getSessionManager") public void testInvalidate2(InternalSessionManager sessionManager) { Assert.assertEquals(sessionManager.getActiveSessions(), 0); WxSession session = ((WxSessionManager) sessionManager).getSession("abc"); Assert.assertEquals(sessionManager.getActiveSessions(), 1); session.invalidate(); Assert.assertEquals(sessionManager.getActiveSessions(), 0); } @Test(dataProvider = "getSessionManager") public void testGetSession(WxSessionManager sessionManager) { WxSession session1 = sessionManager.getSession("abc"); WxSession session2 = sessionManager.getSession("abc"); Assert.assertEquals(session1, session2); Assert.assertTrue(session1 == session2); WxSession abc1 = sessionManager.getSession("abc1"); Assert.assertNotEquals(session1, abc1); WxSession abc1b = sessionManager.getSession("abc1", false); Assert.assertEquals(abc1, abc1b); WxSession def = sessionManager.getSession("def", false); Assert.assertNull(def); } @Test(dataProvider = "getSessionManager") public void testInvalidateAngGet(WxSessionManager sessionManager) { WxSession session1 = sessionManager.getSession("abc"); session1.invalidate(); WxSession session2 = sessionManager.getSession("abc"); Assert.assertNotEquals(session1, session2); InternalSessionManager ism = (InternalSessionManager) sessionManager; Assert.assertEquals(ism.getActiveSessions(), 1); } @Test(dataProvider = "getSessionManager") public void testBackgroundProcess(WxSessionManager sessionManager) throws InterruptedException { InternalSessionManager ism = (InternalSessionManager) sessionManager; ism.setMaxInactiveInterval(1); ism.setProcessExpiresFrequency(1); ism.setBackgroundProcessorDelay(1); Assert.assertEquals(ism.getActiveSessions(), 0); InternalSession abc = ism.createSession("abc"); abc.endAccess(); Thread.sleep(2000); Assert.assertEquals(ism.getActiveSessions(), 0); } @Test(dataProvider = "getSessionManager") public void testBackgroundProcess2(WxSessionManager sessionManager) throws InterruptedException { InternalSessionManager ism = (InternalSessionManager) sessionManager; ism.setMaxInactiveInterval(100); ism.setProcessExpiresFrequency(1); ism.setBackgroundProcessorDelay(1); Assert.assertEquals(ism.getActiveSessions(), 0); InternalSession abc = ism.createSession("abc"); abc.setMaxInactiveInterval(1); abc.endAccess(); Thread.sleep(2000); Assert.assertEquals(ism.getActiveSessions(), 0); } @Test(dataProvider = "getSessionManager") public void testMaxActive(WxSessionManager sessionManager) { InternalSessionManager ism = (InternalSessionManager) sessionManager; ism.setMaxActiveSessions(2); ism.createSession("abc"); ism.createSession("abc"); ism.createSession("def"); } @Test(dataProvider = "getSessionManager", expectedExceptions = TooManyActiveSessionsException.class) public void testMaxActive2(WxSessionManager sessionManager) { InternalSessionManager ism = (InternalSessionManager) sessionManager; ism.setMaxActiveSessions(2); ism.createSession("abc"); ism.createSession("abc"); ism.createSession("def"); ism.createSession("xyz"); } }
java
Apache-2.0
84b5c4d2d0774f800237634e5d0336f53c004fe3
2026-01-04T14:46:39.499027Z
false
binarywang/WxJava
https://github.com/binarywang/WxJava/blob/84b5c4d2d0774f800237634e5d0336f53c004fe3/weixin-java-common/src/test/java/me/chanjar/weixin/common/bean/WxMenuTest.java
weixin-java-common/src/test/java/me/chanjar/weixin/common/bean/WxMenuTest.java
package me.chanjar.weixin.common.bean; import me.chanjar.weixin.common.bean.menu.WxMenu; import me.chanjar.weixin.common.bean.menu.WxMenuButton; import me.chanjar.weixin.common.bean.menu.WxMenuRule; import org.testng.*; import org.testng.annotations.*; @Test public class WxMenuTest { @Test(dataProvider = "wxReturnMenu") public void testFromJson(String json) { WxMenu menu = WxMenu.fromJson(json); Assert.assertEquals(menu.getButtons().size(), 3); } @Test(dataProvider = "wxPushMenu") public void testToJson(String json) { WxMenu menu = new WxMenu(); WxMenuButton button1 = new WxMenuButton(); button1.setType("click"); button1.setName("今日歌曲"); button1.setKey("V1001_TODAY_MUSIC"); WxMenuButton button2 = new WxMenuButton(); button2.setType("click"); button2.setName("歌手简介"); button2.setKey("V1001_TODAY_SINGER"); WxMenuButton button3 = new WxMenuButton(); button3.setName("菜单"); menu.getButtons().add(button1); menu.getButtons().add(button2); menu.getButtons().add(button3); WxMenuButton button31 = new WxMenuButton(); button31.setType("view"); button31.setName("搜索"); button31.setUrl("http://www.soso.com/"); WxMenuButton button32 = new WxMenuButton(); button32.setType("view"); button32.setName("视频"); button32.setUrl("http://v.qq.com/"); WxMenuButton button33 = new WxMenuButton(); button33.setType("click"); button33.setName("赞一下我们"); button33.setKey("V1001_GOOD"); button3.getSubButtons().add(button31); button3.getSubButtons().add(button32); button3.getSubButtons().add(button33); Assert.assertEquals(menu.toJson(), json); } @Test(dataProvider = "wxAddConditionalMenu") public void testAddConditionalToJson(String json) { WxMenu menu = new WxMenu(); WxMenuButton button1 = new WxMenuButton(); button1.setType("click"); button1.setName("今日歌曲"); button1.setKey("V1001_TODAY_MUSIC"); menu.getButtons().add(button1); WxMenuRule wxMenuRule = new WxMenuRule(); wxMenuRule.setTagId("2"); wxMenuRule.setSex("1"); wxMenuRule.setCountry("中国"); wxMenuRule.setProvince("广东"); wxMenuRule.setCity("广州"); wxMenuRule.setClientPlatformType("2"); wxMenuRule.setLanguage("zh_CN"); menu.setMatchRule(wxMenuRule); Assert.assertEquals(menu.toJson(), json); } @DataProvider public Object[][] wxReturnMenu() { Object[][] res = menuJson(); String json = "{ \"menu\" : " + res[0][0] + " }"; return new Object[][]{ new Object[]{json} }; } @DataProvider(name = "wxPushMenu") public Object[][] menuJson() { String json = "{" + "\"button\":[" + "{" + "\"type\":\"click\"," + "\"name\":\"今日歌曲\"," + "\"key\":\"V1001_TODAY_MUSIC\"" + "}," + "{" + "\"type\":\"click\"," + "\"name\":\"歌手简介\"," + "\"key\":\"V1001_TODAY_SINGER\"" + "}," + "{" + "\"name\":\"菜单\"," + "\"sub_button\":[" + "{" + "\"type\":\"view\"," + "\"name\":\"搜索\"," + "\"url\":\"http://www.soso.com/\"" + "}," + "{" + "\"type\":\"view\"," + "\"name\":\"视频\"," + "\"url\":\"http://v.qq.com/\"" + "}," + "{" + "\"type\":\"click\"," + "\"name\":\"赞一下我们\"," + "\"key\":\"V1001_GOOD\"" + "}" + "]" + "}" + "]" + "}"; return new Object[][]{ new Object[]{json} }; } @DataProvider(name = "wxAddConditionalMenu") public Object[][] addConditionalMenuJson() { String json = "{" + "\"button\":[" + "{" + "\"type\":\"click\"," + "\"name\":\"今日歌曲\"," + "\"key\":\"V1001_TODAY_MUSIC\"" + "}" + "]," + "\"matchrule\":{" + "\"group_id\":\"2\"," + "\"sex\":\"1\"," + "\"country\":\"中国\"," + "\"province\":\"广东\"," + "\"city\":\"广州\"," + "\"client_platform_type\":\"2\"," + "\"language\":\"zh_CN\"" + "}" + "}"; return new Object[][]{ new Object[]{json} }; } }
java
Apache-2.0
84b5c4d2d0774f800237634e5d0336f53c004fe3
2026-01-04T14:46:39.499027Z
false
binarywang/WxJava
https://github.com/binarywang/WxJava/blob/84b5c4d2d0774f800237634e5d0336f53c004fe3/weixin-java-common/src/test/java/me/chanjar/weixin/common/bean/WxAccessTokenTest.java
weixin-java-common/src/test/java/me/chanjar/weixin/common/bean/WxAccessTokenTest.java
package me.chanjar.weixin.common.bean; import org.testng.*; import org.testng.annotations.*; @Test public class WxAccessTokenTest { public void testFromJson() { String json = "{\"access_token\":\"ACCESS_TOKEN\",\"expires_in\":7200}"; WxAccessToken wxError = WxAccessToken.fromJson(json); Assert.assertEquals(wxError.getAccessToken(), "ACCESS_TOKEN"); Assert.assertTrue(wxError.getExpiresIn() == 7200); } }
java
Apache-2.0
84b5c4d2d0774f800237634e5d0336f53c004fe3
2026-01-04T14:46:39.499027Z
false
binarywang/WxJava
https://github.com/binarywang/WxJava/blob/84b5c4d2d0774f800237634e5d0336f53c004fe3/weixin-java-common/src/test/java/me/chanjar/weixin/common/bean/WxNetCheckResultTest.java
weixin-java-common/src/test/java/me/chanjar/weixin/common/bean/WxNetCheckResultTest.java
package me.chanjar.weixin.common.bean; import org.testng.Assert; import org.testng.annotations.Test; /** * * @author <a href="https://github.com/binarywang">Binary Wang</a> * created on 2020-06-06 */ public class WxNetCheckResultTest { @Test public void testFromJson() { String json = "{\n" + " \"dns\": [\n" + " {\n" + " \"ip\": \"111.161.64.40\", \n" + " \"real_operator\": \"UNICOM\"\n" + " }, \n" + " {\n" + " \"ip\": \"111.161.64.48\", \n" + " \"real_operator\": \"UNICOM\"\n" + " }\n" + " ], \n" + " \"ping\": [\n" + " {\n" + " \"ip\": \"111.161.64.40\", \n" + " \"from_operator\": \"UNICOM\"," + " \"package_loss\": \"0%\", \n" + " \"time\": \"23.079ms\"\n" + " }, \n" + " {\n" + " \"ip\": \"111.161.64.48\", \n" + " \"from_operator\": \"UNICOM\", \n" + " \"package_loss\": \"0%\", \n" + " \"time\": \"21.434ms\"\n" + " }\n" + " ]\n" + "}"; WxNetCheckResult result = WxNetCheckResult.fromJson(json); Assert.assertNotNull(result); Assert.assertNotNull(result.getDnsInfos()); WxNetCheckResult.WxNetCheckDnsInfo dnsInfo = new WxNetCheckResult.WxNetCheckDnsInfo(); dnsInfo.setIp("111.161.64.40"); dnsInfo.setRealOperator("UNICOM"); Assert.assertEquals(result.getDnsInfos().get(0), dnsInfo); WxNetCheckResult.WxNetCheckPingInfo pingInfo = new WxNetCheckResult.WxNetCheckPingInfo(); pingInfo.setTime("21.434ms"); pingInfo.setFromOperator("UNICOM"); pingInfo.setIp("111.161.64.48"); pingInfo.setPackageLoss("0%"); Assert.assertEquals(result.getPingInfos().get(1), pingInfo); } }
java
Apache-2.0
84b5c4d2d0774f800237634e5d0336f53c004fe3
2026-01-04T14:46:39.499027Z
false
binarywang/WxJava
https://github.com/binarywang/WxJava/blob/84b5c4d2d0774f800237634e5d0336f53c004fe3/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/SignUtils.java
weixin-java-common/src/main/java/me/chanjar/weixin/common/util/SignUtils.java
package me.chanjar.weixin.common.util; import java.nio.charset.StandardCharsets; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; import javax.crypto.Mac; import javax.crypto.spec.SecretKeySpec; import org.apache.commons.codec.binary.Hex; import lombok.extern.slf4j.Slf4j; /** * <pre> * 签名工具类 * Created by BinaryWang on 2018/7/11. * </pre> * * @author <a href="https://github.com/binarywang">Binary Wang</a> */ @Slf4j public class SignUtils { /** * HmacSHA256 签名算法 * * @param message 签名数据 * @param key 签名密钥 */ public static String createHmacSha256Sign(String message, String key) { try { Mac sha256 = Mac.getInstance("HmacSHA256"); SecretKeySpec secretKeySpec = new SecretKeySpec(key.getBytes(StandardCharsets.UTF_8), "HmacSHA256"); sha256.init(secretKeySpec); byte[] bytes = sha256.doFinal(message.getBytes(StandardCharsets.UTF_8)); return Hex.encodeHexString(bytes).toUpperCase(); } catch (NoSuchAlgorithmException | InvalidKeyException e) { SignUtils.log.error(e.getMessage(), e); } return null; } }
java
Apache-2.0
84b5c4d2d0774f800237634e5d0336f53c004fe3
2026-01-04T14:46:39.499027Z
false
binarywang/WxJava
https://github.com/binarywang/WxJava/blob/84b5c4d2d0774f800237634e5d0336f53c004fe3/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/LogExceptionHandler.java
weixin-java-common/src/main/java/me/chanjar/weixin/common/util/LogExceptionHandler.java
package me.chanjar.weixin.common.util; import lombok.extern.slf4j.Slf4j; import me.chanjar.weixin.common.api.WxErrorExceptionHandler; import me.chanjar.weixin.common.error.WxErrorException; /** * @author Daniel Qian */ @Slf4j public class LogExceptionHandler implements WxErrorExceptionHandler { @Override public void handle(WxErrorException e) { log.error("Error happens", e); } }
java
Apache-2.0
84b5c4d2d0774f800237634e5d0336f53c004fe3
2026-01-04T14:46:39.499027Z
false
binarywang/WxJava
https://github.com/binarywang/WxJava/blob/84b5c4d2d0774f800237634e5d0336f53c004fe3/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/RandomUtils.java
weixin-java-common/src/main/java/me/chanjar/weixin/common/util/RandomUtils.java
package me.chanjar.weixin.common.util; public class RandomUtils { private static final String RANDOM_STR = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; private static volatile java.util.Random random; private static java.util.Random getRandom() { if (random == null) { synchronized (RandomUtils.class) { if (random == null) { random = new java.util.Random(); } } } return random; } public static String getRandomStr() { StringBuilder sb = new StringBuilder(); java.util.Random r = getRandom(); for (int i = 0; i < 16; i++) { sb.append(RANDOM_STR.charAt(r.nextInt(RANDOM_STR.length()))); } return sb.toString(); } }
java
Apache-2.0
84b5c4d2d0774f800237634e5d0336f53c004fe3
2026-01-04T14:46:39.499027Z
false
binarywang/WxJava
https://github.com/binarywang/WxJava/blob/84b5c4d2d0774f800237634e5d0336f53c004fe3/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/DataUtils.java
weixin-java-common/src/main/java/me/chanjar/weixin/common/util/DataUtils.java
package me.chanjar.weixin.common.util; import org.apache.commons.lang3.RegExUtils; import org.apache.commons.lang3.StringUtils; /** * <pre> * 数据处理工具类 * Created by BinaryWang on 2018/5/8. * </pre> * * @author <a href="https://github.com/binarywang">Binary Wang</a> */ public class DataUtils { /** * 将数据中包含的secret字符使用星号替换,防止日志打印时被输出 */ public static <E> E handleDataWithSecret(E data) { E dataForLog = data; if(data instanceof String && StringUtils.contains((String)data, "&secret=")){ dataForLog = (E) RegExUtils.replaceAll((String)data,"&secret=\\w+&","&secret=******&"); } return dataForLog; } }
java
Apache-2.0
84b5c4d2d0774f800237634e5d0336f53c004fe3
2026-01-04T14:46:39.499027Z
false
binarywang/WxJava
https://github.com/binarywang/WxJava/blob/84b5c4d2d0774f800237634e5d0336f53c004fe3/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/XmlUtils.java
weixin-java-common/src/main/java/me/chanjar/weixin/common/util/XmlUtils.java
package me.chanjar.weixin.common.util; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.google.common.collect.Sets; import me.chanjar.weixin.common.error.WxRuntimeException; import org.dom4j.*; import org.dom4j.io.SAXReader; import org.dom4j.tree.DefaultText; import org.xml.sax.SAXException; import java.io.StringReader; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.stream.Collectors; /** * <pre> * XML转换工具类. * Created by Binary Wang on 2018/11/4. * </pre> * * @author <a href="https://github.com/binarywang">Binary Wang</a> */ public class XmlUtils { public static Map<String, Object> xml2Map(String xmlString) { Map<String, Object> map = new HashMap<>(16); try { SAXReader saxReader = new SAXReader(); saxReader.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true); saxReader.setFeature("http://javax.xml.XMLConstants/feature/secure-processing", true); saxReader.setFeature("http://xml.org/sax/features/external-parameter-entities", false); saxReader.setFeature("http://xml.org/sax/features/external-general-entities", false); saxReader.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false); Document doc = saxReader.read(new StringReader(xmlString)); Element root = doc.getRootElement(); List<Element> elements = root.elements(); for (Element element : elements) { String elementName = element.getName(); if (map.containsKey(elementName)) { if (map.get(elementName) instanceof List) { ((List<Object>) map.get(elementName)).add(element2MapOrString(element)); } else { List<Object> value = Lists.newArrayList(map.get(elementName)); value.add(element2MapOrString(element)); map.put(elementName, value); } } else { map.put(elementName, element2MapOrString(element)); } } } catch (DocumentException | SAXException e) { throw new WxRuntimeException(e); } return map; } private static Object element2MapOrString(Element element) { final List<Node> nodes = element.content(); final List<String> names = names(nodes); // 判断节点下有无非文本节点(非Text和CDATA),如无,直接取Text文本内容 if (names.isEmpty()) { return element.getText(); } Map<String, Object> result = Maps.newHashMap(); Set<String> distinctNames = Sets.newHashSet(names); if (distinctNames.size() == 1) { // 说明是个列表,各个子对象是相同的name List<Object> list = Lists.newArrayList(); for (Node node : nodes) { if (node instanceof DefaultText) { continue; } if (node instanceof Element) { list.add(element2MapOrString((Element) node)); } } result.put(names.iterator().next(), list); } else if (distinctNames.size() == names.size()) { for (Node node : nodes) { if (node instanceof DefaultText) { continue; } if (node instanceof Element) { result.put(node.getName(), element2MapOrString((Element) node)); } } } else { // 说明有重复name,但不是全部都相同 Map<String, Long> namesCountMap = names.stream().collect(Collectors.groupingBy(a -> a, Collectors.counting())); for (Node node : nodes) { if (node instanceof DefaultText) { continue; } if (node instanceof Element) { String nodeName = node.getName(); if (namesCountMap.get(nodeName) == 1) { result.put(nodeName, element2MapOrString((Element) node)); } else { List<Object> values; if (result.containsKey(nodeName)) { values = (List<Object>) result.get(nodeName); } else { values = Lists.newArrayList(); result.put(nodeName, values); } values.add(element2MapOrString((Element) node)); } } } } return result; } private static List<String> names(List<Node> nodes) { List<String> names = Lists.newArrayList(); for (Node node : nodes) { // 如果节点类型是Text或CDATA跳过 if (node instanceof DefaultText || node instanceof CDATA) { continue; } names.add(node.getName()); } return names; } }
java
Apache-2.0
84b5c4d2d0774f800237634e5d0336f53c004fe3
2026-01-04T14:46:39.499027Z
false
binarywang/WxJava
https://github.com/binarywang/WxJava/blob/84b5c4d2d0774f800237634e5d0336f53c004fe3/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/BeanUtils.java
weixin-java-common/src/main/java/me/chanjar/weixin/common/util/BeanUtils.java
package me.chanjar.weixin.common.util; import com.google.common.collect.Lists; import me.chanjar.weixin.common.annotation.Required; import me.chanjar.weixin.common.error.WxErrorException; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.lang.reflect.Field; import java.util.ArrayList; import java.util.Arrays; import java.util.List; /** * <pre> * bean操作的一些工具类 * Created by Binary Wang on 2016-10-21. * </pre> * * @author <a href="https://github.com/binarywang">binarywang(Binary Wang)</a> */ public class BeanUtils { private static Logger log = LoggerFactory.getLogger(BeanUtils.class); /** * 检查bean里标记为@Required的field是否为空,为空则抛异常 * * @param bean 要检查的bean对象 */ public static void checkRequiredFields(Object bean) throws WxErrorException { List<String> requiredFields = Lists.newArrayList(); List<Field> fields = new ArrayList<>(Arrays.asList(bean.getClass().getDeclaredFields())); fields.addAll(Arrays.asList(bean.getClass().getSuperclass().getDeclaredFields())); for (Field field : fields) { try { boolean isAccessible = field.isAccessible(); field.setAccessible(true); if (field.isAnnotationPresent(Required.class)) { // 两种情况,一种是值为null, // 另外一种情况是类型为字符串,但是字符串内容为空的,都认为是没有提供值 boolean isRequiredMissing = field.get(bean) == null || (field.get(bean) instanceof String && StringUtils.isBlank(field.get(bean).toString()) ); if (isRequiredMissing) { requiredFields.add(field.getName()); } } field.setAccessible(isAccessible); } catch (SecurityException | IllegalArgumentException | IllegalAccessException e) { log.error(e.getMessage(), e); } } if (!requiredFields.isEmpty()) { String msg = String.format("必填字段【%s】必须提供值!", requiredFields); log.debug(msg); throw new WxErrorException(msg); } } }
java
Apache-2.0
84b5c4d2d0774f800237634e5d0336f53c004fe3
2026-01-04T14:46:39.499027Z
false
binarywang/WxJava
https://github.com/binarywang/WxJava/blob/84b5c4d2d0774f800237634e5d0336f53c004fe3/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/res/StringManager.java
weixin-java-common/src/main/java/me/chanjar/weixin/common/util/res/StringManager.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package me.chanjar.weixin.common.util.res; import java.text.MessageFormat; import java.util.*; import java.util.concurrent.ConcurrentHashMap; /** * An internationalization / localization helper class which reduces * the bother of handling ResourceBundles and takes care of the * common cases of message formating which otherwise require the * creation of Object arrays and such. * <p> * <p>The StringManager operates on a package basis. One StringManager * per package can be created and accessed via the getManager method * call. * <p> * <p>The StringManager will look for a ResourceBundle named by * the package name given plus the suffix of "LocalStrings". In * practice, this means that the localized information will be contained * in a LocalStrings.properties file located in the package * directory of the classpath. * <p> * <p>Please see the documentation for java.util.ResourceBundle for * more information. * * @author James Duncan Davidson [duncan@eng.sun.com] * @author James Todd [gonzo@eng.sun.com] * @author Mel Martinez [mmartinez@g1440.com] * @see java.util.ResourceBundle */ public class StringManager { private static final Map<String, Map<Locale, StringManager>> MANAGERS = new ConcurrentHashMap<>(); private static int LOCALE_CACHE_SIZE = 10; /** * The ResourceBundle for this StringManager. */ private final ResourceBundle bundle; private final Locale locale; /** * Creates a new StringManager for a given package. This is a * private method and all access to it is arbitrated by the * static getManager method call so that only one StringManager * per package will be created. * * @param packageName Name of package to create StringManager for. */ private StringManager(String packageName, Locale locale) { String bundleName = packageName + ".LocalStrings"; ResourceBundle bnd = null; try { bnd = ResourceBundle.getBundle(bundleName, locale); } catch (MissingResourceException ex) { // Try from the current loader (that's the case for trusted apps) // Should only be required if using a TC5 style classloader structure // where common != shared != server ClassLoader cl = Thread.currentThread().getContextClassLoader(); if (cl != null) { try { bnd = ResourceBundle.getBundle(bundleName, locale, cl); } catch (MissingResourceException ex2) { // Ignore } } } this.bundle = bnd; // Get the actual locale, which may be different from the requested one if (this.bundle != null) { Locale bundleLocale = this.bundle.getLocale(); if (bundleLocale.equals(Locale.ROOT)) { this.locale = Locale.ENGLISH; } else { this.locale = bundleLocale; } } else { this.locale = null; } } /** * Get the StringManager for a particular package. If a manager for * a package already exists, it will be reused, else a new * StringManager will be created and returned. * * @param packageName The package name */ public static synchronized StringManager getManager( String packageName) { return getManager(packageName, Locale.getDefault()); } /** * Get the StringManager for a particular package and Locale. If a manager * for a package/Locale combination already exists, it will be reused, else * a new StringManager will be created and returned. * * @param packageName The package name * @param locale The Locale */ public static synchronized StringManager getManager( String packageName, Locale locale) { Map<Locale, StringManager> map = MANAGERS.get(packageName); if (map == null) { /* * Don't want the HashMap to be expanded beyond LOCALE_CACHE_SIZE. * Expansion occurs when size() exceeds capacity. Therefore keep * size at or below capacity. * removeEldestEntry() executes after insertion therefore the test * for removal needs to use one less than the maximum desired size * */ map = new LinkedHashMap<Locale, StringManager>(LOCALE_CACHE_SIZE, 1, true) { private static final long serialVersionUID = 1L; @Override protected boolean removeEldestEntry( Map.Entry<Locale, StringManager> eldest) { return size() > (LOCALE_CACHE_SIZE - 1); } }; MANAGERS.put(packageName, map); } StringManager mgr = map.get(locale); if (mgr == null) { mgr = new StringManager(packageName, locale); map.put(locale, mgr); } return mgr; } // -------------------------------------------------------------- // STATIC SUPPORT METHODS // -------------------------------------------------------------- /** * Retrieve the StringManager for a list of Locales. The first StringManager * found will be returned. * * @param requestedLocales the list of Locales * @return the found StringManager or the default StringManager */ public static StringManager getManager(String packageName, Enumeration<Locale> requestedLocales) { while (requestedLocales.hasMoreElements()) { Locale locale = requestedLocales.nextElement(); StringManager result = getManager(packageName, locale); if (result.getLocale().equals(locale)) { return result; } } // Return the default return getManager(packageName); } /** * Get a string from the underlying resource bundle or return * null if the String is not found. * * @param key to desired resource String * @return resource String matching <i>key</i> from underlying * bundle or null if not found. * @throws IllegalArgumentException if <i>key</i> is null. */ public String getString(String key) { if (key == null) { String msg = "key may not have a null value"; throw new IllegalArgumentException(msg); } String str = null; try { // Avoid NPE if bundle is null and treat it like an MRE if (this.bundle != null) { str = this.bundle.getString(key); } } catch (MissingResourceException mre) { //bad: shouldn't mask an exception the following way: // str = "[cannot find message associated with key '" + key + // "' due to " + mre + "]"; // because it hides the fact that the String was missing // from the calling code. //good: could just throw the exception (or wrap it in another) // but that would probably cause much havoc on existing // code. //better: consistent with container pattern to // simply return null. Calling code can then do // a null check. str = null; } return str; } /** * Get a string from the underlying resource bundle and format * it with the given set of arguments. * * @param key * @param args */ public String getString(final String key, final Object... args) { String value = getString(key); if (value == null) { value = key; } MessageFormat mf = new MessageFormat(value); mf.setLocale(this.locale); return mf.format(args, new StringBuffer(), null).toString(); } /** * Identify the Locale this StringManager is associated with */ public Locale getLocale() { return this.locale; } }
java
Apache-2.0
84b5c4d2d0774f800237634e5d0336f53c004fe3
2026-01-04T14:46:39.499027Z
false
binarywang/WxJava
https://github.com/binarywang/WxJava/blob/84b5c4d2d0774f800237634e5d0336f53c004fe3/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/xml/IntegerArrayConverter.java
weixin-java-common/src/main/java/me/chanjar/weixin/common/util/xml/IntegerArrayConverter.java
package me.chanjar.weixin.common.util.xml; import com.google.common.base.Joiner; import com.google.common.base.Splitter; import com.google.common.collect.Iterables; import com.thoughtworks.xstream.converters.basic.StringConverter; /** * Integer型数组转换器. * * @author <a href="https://github.com/binarywang">Binary Wang</a> * created on 2019-08-22 */ public class IntegerArrayConverter extends StringConverter { @Override public boolean canConvert(Class type) { return type == Integer[].class; } @Override public String toString(Object obj) { return "<![CDATA[" + Joiner.on(",").join((Integer[]) obj) + "]]>"; } @Override public Object fromString(String str) { if (str == null || str.isEmpty()) { return null; } final Iterable<String> iterable = Splitter.on(",").split(str); final String[] strings = Iterables.toArray(iterable, String.class); Integer[] result = new Integer[strings.length]; int index = 0; for (String string : strings) { result[index++] = Integer.parseInt(string); } return result; } }
java
Apache-2.0
84b5c4d2d0774f800237634e5d0336f53c004fe3
2026-01-04T14:46:39.499027Z
false
binarywang/WxJava
https://github.com/binarywang/WxJava/blob/84b5c4d2d0774f800237634e5d0336f53c004fe3/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/xml/StringArrayConverter.java
weixin-java-common/src/main/java/me/chanjar/weixin/common/util/xml/StringArrayConverter.java
package me.chanjar.weixin.common.util.xml; import com.google.common.base.Joiner; import com.google.common.base.Splitter; import com.google.common.collect.Iterables; import com.thoughtworks.xstream.converters.basic.StringConverter; /** * String 数组转换 * @author chily.lin */ public class StringArrayConverter extends StringConverter { @Override public boolean canConvert(Class type) { return type == String[].class; } @Override public String toString(Object obj) { return "<![CDATA[" + Joiner.on(",").join((String[]) obj) + "]]>"; } @Override public Object fromString(String str) { final Iterable<String> iterable = Splitter.on(",").split(str); String[] results = Iterables.toArray(iterable, String.class); return results; } }
java
Apache-2.0
84b5c4d2d0774f800237634e5d0336f53c004fe3
2026-01-04T14:46:39.499027Z
false
binarywang/WxJava
https://github.com/binarywang/WxJava/blob/84b5c4d2d0774f800237634e5d0336f53c004fe3/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/xml/XStreamReplaceNameConverter.java
weixin-java-common/src/main/java/me/chanjar/weixin/common/util/xml/XStreamReplaceNameConverter.java
package me.chanjar.weixin.common.util.xml; public class XStreamReplaceNameConverter extends XStreamCDataConverter { @Override public String toString(Object obj) { return "<ReplaceName>" + super.toString(obj) + "</ReplaceName>"; } }
java
Apache-2.0
84b5c4d2d0774f800237634e5d0336f53c004fe3
2026-01-04T14:46:39.499027Z
false
binarywang/WxJava
https://github.com/binarywang/WxJava/blob/84b5c4d2d0774f800237634e5d0336f53c004fe3/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/xml/XStreamMediaIdConverter.java
weixin-java-common/src/main/java/me/chanjar/weixin/common/util/xml/XStreamMediaIdConverter.java
package me.chanjar.weixin.common.util.xml; public class XStreamMediaIdConverter extends XStreamCDataConverter { @Override public String toString(Object obj) { return "<MediaId>" + super.toString(obj) + "</MediaId>"; } }
java
Apache-2.0
84b5c4d2d0774f800237634e5d0336f53c004fe3
2026-01-04T14:46:39.499027Z
false
binarywang/WxJava
https://github.com/binarywang/WxJava/blob/84b5c4d2d0774f800237634e5d0336f53c004fe3/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/xml/XStreamCDataConverter.java
weixin-java-common/src/main/java/me/chanjar/weixin/common/util/xml/XStreamCDataConverter.java
package me.chanjar.weixin.common.util.xml; import com.thoughtworks.xstream.converters.basic.StringConverter; /** * CDATA 内容转换器,加上CDATA标签. * * @author Daniel Qian */ public class XStreamCDataConverter extends StringConverter { @Override public String toString(Object obj) { return "<![CDATA[" + super.toString(obj) + "]]>"; } }
java
Apache-2.0
84b5c4d2d0774f800237634e5d0336f53c004fe3
2026-01-04T14:46:39.499027Z
false
binarywang/WxJava
https://github.com/binarywang/WxJava/blob/84b5c4d2d0774f800237634e5d0336f53c004fe3/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/xml/LongArrayConverter.java
weixin-java-common/src/main/java/me/chanjar/weixin/common/util/xml/LongArrayConverter.java
package me.chanjar.weixin.common.util.xml; import com.google.common.base.Joiner; import com.google.common.base.Splitter; import com.google.common.collect.Iterables; import com.thoughtworks.xstream.converters.basic.StringConverter; /** * Long型数组转换器. * * @author <a href="https://github.com/binarywang">Binary Wang</a> * created on 2019-08-22 */ public class LongArrayConverter extends StringConverter { @Override public boolean canConvert(Class type) { return type == Long[].class; } @Override public String toString(Object obj) { return "<![CDATA[" + Joiner.on(",").join((Long[]) obj) + "]]>"; } @Override public Object fromString(String str) { final Iterable<String> iterable = Splitter.on(",").split(str); final String[] strings = Iterables.toArray(iterable, String.class); Long[] result = new Long[strings.length]; int index = 0; for (String string : strings) { result[index++] = Long.parseLong(string); } return result; } }
java
Apache-2.0
84b5c4d2d0774f800237634e5d0336f53c004fe3
2026-01-04T14:46:39.499027Z
false
binarywang/WxJava
https://github.com/binarywang/WxJava/blob/84b5c4d2d0774f800237634e5d0336f53c004fe3/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/xml/XStreamInitializer.java
weixin-java-common/src/main/java/me/chanjar/weixin/common/util/xml/XStreamInitializer.java
package me.chanjar.weixin.common.util.xml; import com.thoughtworks.xstream.XStream; import com.thoughtworks.xstream.converters.basic.*; import com.thoughtworks.xstream.converters.collections.CollectionConverter; import com.thoughtworks.xstream.converters.reflection.PureJavaReflectionProvider; import com.thoughtworks.xstream.converters.reflection.ReflectionConverter; import com.thoughtworks.xstream.core.util.QuickWriter; import com.thoughtworks.xstream.io.HierarchicalStreamWriter; import com.thoughtworks.xstream.io.xml.PrettyPrintWriter; import com.thoughtworks.xstream.io.xml.XppDriver; import com.thoughtworks.xstream.security.NoTypePermission; import com.thoughtworks.xstream.security.WildcardTypePermission; import java.io.Writer; /** * The type X stream initializer. * * @author Daniel Qian */ public class XStreamInitializer { public static ClassLoader classLoader; public static void setClassLoader(ClassLoader classLoaderInfo) { classLoader = classLoaderInfo; } private static final XppDriver XPP_DRIVER = new XppDriver() { @Override public HierarchicalStreamWriter createWriter(Writer out) { return new PrettyPrintWriter(out, getNameCoder()) { private static final String PREFIX_CDATA = "<![CDATA["; private static final String SUFFIX_CDATA = "]]>"; private static final String PREFIX_MEDIA_ID = "<MediaId>"; private static final String SUFFIX_MEDIA_ID = "</MediaId>"; private static final String PREFIX_REPLACE_NAME = "<ReplaceName>"; private static final String SUFFIX_REPLACE_NAME = "</ReplaceName>"; @Override protected void writeText(QuickWriter writer, String text) { if (text.startsWith(PREFIX_CDATA) && text.endsWith(SUFFIX_CDATA)) { writer.write(text); } else if (text.startsWith(PREFIX_MEDIA_ID) && text.endsWith(SUFFIX_MEDIA_ID)) { writer.write(text); } else if (text.startsWith(PREFIX_REPLACE_NAME) && text.endsWith(SUFFIX_REPLACE_NAME)){ writer.write(text); } else { super.writeText(writer, text); } } @Override public String encodeNode(String name) { //防止将_转换成__ return name; } }; } }; /** * Gets instance. * * @return the instance */ public static XStream getInstance() { XStream xstream = new XStream(new PureJavaReflectionProvider(), XPP_DRIVER) { // only register the converters we need; other converters generate a private access warning in the console on Java9+... @Override protected void setupConverters() { registerConverter(new NullConverter(), PRIORITY_VERY_HIGH); registerConverter(new IntConverter(), PRIORITY_NORMAL); registerConverter(new FloatConverter(), PRIORITY_NORMAL); registerConverter(new DoubleConverter(), PRIORITY_NORMAL); registerConverter(new LongConverter(), PRIORITY_NORMAL); registerConverter(new ShortConverter(), PRIORITY_NORMAL); registerConverter(new BooleanConverter(), PRIORITY_NORMAL); registerConverter(new ByteConverter(), PRIORITY_NORMAL); registerConverter(new StringConverter(), PRIORITY_NORMAL); registerConverter(new DateConverter(), PRIORITY_NORMAL); registerConverter(new CollectionConverter(getMapper()), PRIORITY_NORMAL); registerConverter(new ReflectionConverter(getMapper(), getReflectionProvider()), PRIORITY_VERY_LOW); } }; xstream.ignoreUnknownElements(); xstream.setMode(XStream.NO_REFERENCES); xstream.autodetectAnnotations(true); // setup proper security by limiting which classes can be loaded by XStream xstream.addPermission(NoTypePermission.NONE); xstream.addPermission(new WildcardTypePermission(new String[]{ "me.chanjar.weixin.**", "cn.binarywang.wx.**", "com.github.binarywang.**" })); if (null == classLoader) { classLoader = Thread.currentThread().getContextClassLoader(); } xstream.setClassLoader(classLoader); return xstream; } }
java
Apache-2.0
84b5c4d2d0774f800237634e5d0336f53c004fe3
2026-01-04T14:46:39.499027Z
false
binarywang/WxJava
https://github.com/binarywang/WxJava/blob/84b5c4d2d0774f800237634e5d0336f53c004fe3/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/locks/JedisDistributedLock.java
weixin-java-common/src/main/java/me/chanjar/weixin/common/util/locks/JedisDistributedLock.java
package me.chanjar.weixin.common.util.locks; import java.util.concurrent.TimeUnit; import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.Lock; import com.github.jedis.lock.JedisLock; import me.chanjar.weixin.common.error.WxRuntimeException; import redis.clients.jedis.Jedis; import redis.clients.jedis.util.Pool; /** * JedisPool 分布式锁 * @deprecated 不建议使用jedis-lock这个过期组件,不可靠 * * @author <a href="https://github.com/007gzs">007</a> */ @Deprecated public class JedisDistributedLock implements Lock { private final Pool<Jedis> jedisPool; private final JedisLock lock; public JedisDistributedLock(Pool<Jedis> jedisPool, String key){ this.jedisPool = jedisPool; this.lock = new JedisLock(key); } @Override public void lock() { try (Jedis jedis = jedisPool.getResource()) { if (!lock.acquire(jedis)) { throw new WxRuntimeException("acquire timeouted"); } } catch (InterruptedException e) { throw new WxRuntimeException("lock failed", e); } } @Override public void lockInterruptibly() throws InterruptedException { try (Jedis jedis = jedisPool.getResource()) { if (!lock.acquire(jedis)) { throw new WxRuntimeException("acquire timeouted"); } } } @Override public boolean tryLock() { try (Jedis jedis = jedisPool.getResource()) { return lock.acquire(jedis); } catch (InterruptedException e) { throw new WxRuntimeException("lock failed", e); } } @Override public boolean tryLock(long time, TimeUnit unit) throws InterruptedException { try (Jedis jedis = jedisPool.getResource()) { return lock.acquire(jedis); } } @Override public void unlock() { try (Jedis jedis = jedisPool.getResource()) { lock.release(jedis); } } @Override public Condition newCondition() { throw new WxRuntimeException("unsupported method"); } }
java
Apache-2.0
84b5c4d2d0774f800237634e5d0336f53c004fe3
2026-01-04T14:46:39.499027Z
false
binarywang/WxJava
https://github.com/binarywang/WxJava/blob/84b5c4d2d0774f800237634e5d0336f53c004fe3/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/locks/RedisTemplateSimpleDistributedLock.java
weixin-java-common/src/main/java/me/chanjar/weixin/common/util/locks/RedisTemplateSimpleDistributedLock.java
package me.chanjar.weixin.common.util.locks; import lombok.Getter; import org.springframework.data.redis.core.StringRedisTemplate; import org.springframework.data.redis.core.script.DefaultRedisScript; import org.springframework.data.redis.core.script.RedisScript; import java.util.Collections; import java.util.UUID; import java.util.concurrent.TimeUnit; import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.Lock; /** * 实现简单的redis分布式锁, 支持重入, 不是红锁 * * @see <a href="https://redis.io/topics/distlock">reids distlock</a> */ public class RedisTemplateSimpleDistributedLock implements Lock { @Getter private final StringRedisTemplate redisTemplate; @Getter private final String key; @Getter private final int leaseMilliseconds; private final ThreadLocal<String> valueThreadLocal = new ThreadLocal<>(); public RedisTemplateSimpleDistributedLock( StringRedisTemplate redisTemplate, int leaseMilliseconds) { this(redisTemplate, "lock:" + UUID.randomUUID().toString(), leaseMilliseconds); } public RedisTemplateSimpleDistributedLock( StringRedisTemplate redisTemplate, String key, int leaseMilliseconds) { if (leaseMilliseconds <= 0) { throw new IllegalArgumentException("Parameter 'leaseMilliseconds' must grate then 0: " + leaseMilliseconds); } this.redisTemplate = redisTemplate; this.key = key; this.leaseMilliseconds = leaseMilliseconds; } @Override public void lock() { while (!tryLock()) { try { Thread.sleep(1000); } catch (InterruptedException e) { // Ignore } } } @Override public void lockInterruptibly() throws InterruptedException { while (!tryLock()) { Thread.sleep(1000); } } @Override public boolean tryLock() { String value = valueThreadLocal.get(); if (value == null || value.isEmpty()) { value = UUID.randomUUID().toString(); valueThreadLocal.set(value); } // Use high-level StringRedisTemplate API to ensure consistent key serialization Boolean lockAcquired = redisTemplate.opsForValue().setIfAbsent(key, value, leaseMilliseconds, TimeUnit.MILLISECONDS); if (Boolean.TRUE.equals(lockAcquired)) { return true; } // Check if we already hold the lock (reentrant behavior) String currentValue = redisTemplate.opsForValue().get(key); return value.equals(currentValue); } @Override public boolean tryLock(long time, TimeUnit unit) throws InterruptedException { long waitMs = unit.toMillis(time); boolean locked = tryLock(); while (!locked && waitMs > 0) { long sleep = waitMs < 1000 ? waitMs : 1000; Thread.sleep(sleep); waitMs -= sleep; locked = tryLock(); } return locked; } @Override public void unlock() { if (valueThreadLocal.get() != null) { // 提示: 必须指定returnType, 类型: 此处必须为Long, 不能是Integer RedisScript<Long> script = new DefaultRedisScript<>("if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end", Long.class); redisTemplate.execute(script, Collections.singletonList(key), valueThreadLocal.get()); valueThreadLocal.remove(); } } @Override public Condition newCondition() { throw new UnsupportedOperationException(); } /** * 获取当前锁的值 * return 返回null意味着没有加锁, 但是返回非null值并不以为着当前加锁成功(redis中key可能自动过期) */ public String getLockSecretValue() { return valueThreadLocal.get(); } }
java
Apache-2.0
84b5c4d2d0774f800237634e5d0336f53c004fe3
2026-01-04T14:46:39.499027Z
false
binarywang/WxJava
https://github.com/binarywang/WxJava/blob/84b5c4d2d0774f800237634e5d0336f53c004fe3/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/json/WxBooleanTypeAdapter.java
weixin-java-common/src/main/java/me/chanjar/weixin/common/util/json/WxBooleanTypeAdapter.java
package me.chanjar.weixin.common.util.json; import com.google.gson.JsonParseException; import com.google.gson.TypeAdapter; import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonToken; import com.google.gson.stream.JsonWriter; import org.apache.commons.lang3.BooleanUtils; import java.io.IOException; /** * <pre> * Gson 布尔类型类型转换器 * Created by Binary Wang on 2017-7-8. * </pre> * * @author <a href="https://github.com/binarywang">Binary Wang</a> */ public class WxBooleanTypeAdapter extends TypeAdapter<Boolean> { @Override public void write(JsonWriter out, Boolean value) throws IOException { if (value == null) { out.nullValue(); } else { out.value(value); } } @Override public Boolean read(JsonReader in) throws IOException { JsonToken peek = in.peek(); switch (peek) { case BOOLEAN: return in.nextBoolean(); case NULL: in.nextNull(); return null; case NUMBER: return BooleanUtils.toBoolean(in.nextInt()); case STRING: return BooleanUtils.toBoolean(in.nextString()); default: throw new JsonParseException("Expected BOOLEAN or NUMBER but was " + peek); } } }
java
Apache-2.0
84b5c4d2d0774f800237634e5d0336f53c004fe3
2026-01-04T14:46:39.499027Z
false
binarywang/WxJava
https://github.com/binarywang/WxJava/blob/84b5c4d2d0774f800237634e5d0336f53c004fe3/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/json/WxGsonBuilder.java
weixin-java-common/src/main/java/me/chanjar/weixin/common/util/json/WxGsonBuilder.java
package me.chanjar.weixin.common.util.json; import com.google.gson.ExclusionStrategy; import com.google.gson.FieldAttributes; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import me.chanjar.weixin.common.bean.WxAccessToken; import me.chanjar.weixin.common.bean.WxNetCheckResult; import me.chanjar.weixin.common.bean.menu.WxMenu; import me.chanjar.weixin.common.error.WxError; import me.chanjar.weixin.common.bean.result.WxMediaUploadResult; import me.chanjar.weixin.common.util.http.apache.ApacheHttpClientBuilder; import java.io.File; import java.util.Objects; /** * . * @author chanjarster */ public class WxGsonBuilder { private static final GsonBuilder INSTANCE = new GsonBuilder(); private static volatile Gson GSON_INSTANCE; static { INSTANCE.disableHtmlEscaping(); INSTANCE.registerTypeAdapter(WxAccessToken.class, new WxAccessTokenAdapter()); INSTANCE.registerTypeAdapter(WxError.class, new WxErrorAdapter()); INSTANCE.registerTypeAdapter(WxMenu.class, new WxMenuGsonAdapter()); INSTANCE.registerTypeAdapter(WxMediaUploadResult.class, new WxMediaUploadResultAdapter()); INSTANCE.registerTypeAdapter(WxNetCheckResult.class, new WxNetCheckResultGsonAdapter()); INSTANCE.setExclusionStrategies(new ExclusionStrategy() { @Override public boolean shouldSkipField(FieldAttributes fieldAttributes) { return false; } @Override public boolean shouldSkipClass(Class<?> aClass) { return aClass == File.class || aClass == ApacheHttpClientBuilder.class; } }); } public static Gson create() { if (Objects.isNull(GSON_INSTANCE)) { synchronized (INSTANCE) { if (Objects.isNull(GSON_INSTANCE)) { GSON_INSTANCE = INSTANCE.create(); } } } return GSON_INSTANCE; } }
java
Apache-2.0
84b5c4d2d0774f800237634e5d0336f53c004fe3
2026-01-04T14:46:39.499027Z
false
binarywang/WxJava
https://github.com/binarywang/WxJava/blob/84b5c4d2d0774f800237634e5d0336f53c004fe3/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/json/WxMediaUploadResultAdapter.java
weixin-java-common/src/main/java/me/chanjar/weixin/common/util/json/WxMediaUploadResultAdapter.java
package me.chanjar.weixin.common.util.json; import java.lang.reflect.Type; import com.google.gson.JsonDeserializationContext; import com.google.gson.JsonDeserializer; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonParseException; import me.chanjar.weixin.common.bean.result.WxMediaUploadResult; /** * @author Daniel Qian */ public class WxMediaUploadResultAdapter implements JsonDeserializer<WxMediaUploadResult> { @Override public WxMediaUploadResult deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { WxMediaUploadResult result = new WxMediaUploadResult(); JsonObject jsonObject = json.getAsJsonObject(); if (jsonObject.get("url") != null && !jsonObject.get("url").isJsonNull()) { result.setUrl(GsonHelper.getAsString(jsonObject.get("url"))); } if (jsonObject.get("type") != null && !jsonObject.get("type").isJsonNull()) { result.setType(GsonHelper.getAsString(jsonObject.get("type"))); } if (jsonObject.get("media_id") != null && !jsonObject.get("media_id").isJsonNull()) { result.setMediaId(GsonHelper.getAsString(jsonObject.get("media_id"))); } if (jsonObject.get("thumb_media_id") != null && !jsonObject.get("thumb_media_id").isJsonNull()) { result.setThumbMediaId(GsonHelper.getAsString(jsonObject.get("thumb_media_id"))); } if (jsonObject.get("created_at") != null && !jsonObject.get("created_at").isJsonNull()) { result.setCreatedAt(GsonHelper.getAsPrimitiveLong(jsonObject.get("created_at"))); } return result; } }
java
Apache-2.0
84b5c4d2d0774f800237634e5d0336f53c004fe3
2026-01-04T14:46:39.499027Z
false
binarywang/WxJava
https://github.com/binarywang/WxJava/blob/84b5c4d2d0774f800237634e5d0336f53c004fe3/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/json/WxDateTypeAdapter.java
weixin-java-common/src/main/java/me/chanjar/weixin/common/util/json/WxDateTypeAdapter.java
package me.chanjar.weixin.common.util.json; import com.google.gson.JsonParseException; import com.google.gson.TypeAdapter; import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonToken; import com.google.gson.stream.JsonWriter; import java.io.IOException; import java.util.Date; /** * <pre> * Gson 日期类型转换器 * Created by Binary Wang on 2017-7-8. * </pre> * * @author <a href="https://github.com/binarywang">Binary Wang</a> */ public class WxDateTypeAdapter extends TypeAdapter<Date> { @Override public void write(JsonWriter out, Date value) throws IOException { if (value == null) { out.nullValue(); } else { out.value(value.getTime() / 1000); } } @Override public Date read(JsonReader in) throws IOException { JsonToken peek = in.peek(); switch (peek) { case NULL: in.nextNull(); return null; case NUMBER: return new Date(in.nextInt() * 1000); default: throw new JsonParseException("Expected NUMBER but was " + peek); } } }
java
Apache-2.0
84b5c4d2d0774f800237634e5d0336f53c004fe3
2026-01-04T14:46:39.499027Z
false
binarywang/WxJava
https://github.com/binarywang/WxJava/blob/84b5c4d2d0774f800237634e5d0336f53c004fe3/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/json/WxAccessTokenAdapter.java
weixin-java-common/src/main/java/me/chanjar/weixin/common/util/json/WxAccessTokenAdapter.java
package me.chanjar.weixin.common.util.json; import com.google.gson.*; import me.chanjar.weixin.common.bean.WxAccessToken; import java.lang.reflect.Type; /** * @author Daniel Qian */ public class WxAccessTokenAdapter implements JsonDeserializer<WxAccessToken> { @Override public WxAccessToken deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { WxAccessToken accessToken = new WxAccessToken(); JsonObject accessTokenJsonObject = json.getAsJsonObject(); if (accessTokenJsonObject.get("access_token") != null && !accessTokenJsonObject.get("access_token").isJsonNull()) { accessToken.setAccessToken(GsonHelper.getAsString(accessTokenJsonObject.get("access_token"))); } if (accessTokenJsonObject.get("expires_in") != null && !accessTokenJsonObject.get("expires_in").isJsonNull()) { accessToken.setExpiresIn(GsonHelper.getAsPrimitiveInt(accessTokenJsonObject.get("expires_in"))); } return accessToken; } }
java
Apache-2.0
84b5c4d2d0774f800237634e5d0336f53c004fe3
2026-01-04T14:46:39.499027Z
false
binarywang/WxJava
https://github.com/binarywang/WxJava/blob/84b5c4d2d0774f800237634e5d0336f53c004fe3/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/json/GsonHelper.java
weixin-java-common/src/main/java/me/chanjar/weixin/common/util/json/GsonHelper.java
package me.chanjar.weixin.common.util.json; import com.google.common.collect.Lists; import com.google.gson.JsonArray; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import me.chanjar.weixin.common.error.WxRuntimeException; import java.util.List; public class GsonHelper { public static boolean isNull(JsonElement element) { return element == null || element.isJsonNull(); } public static boolean isNotNull(JsonElement element) { return !isNull(element); } public static Long getLong(JsonObject json, String property) { return getAsLong(json.get(property)); } public static long getPrimitiveLong(JsonObject json, String property) { return getAsPrimitiveLong(json.get(property)); } public static Integer getInteger(JsonObject json, String property) { return getAsInteger(json.get(property)); } public static int getPrimitiveInteger(JsonObject json, String property) { return getAsPrimitiveInt(json.get(property)); } public static Double getDouble(JsonObject json, String property) { return getAsDouble(json.get(property)); } public static double getPrimitiveDouble(JsonObject json, String property) { return getAsPrimitiveDouble(json.get(property)); } public static Float getFloat(JsonObject json, String property) { return getAsFloat(json.get(property)); } public static float getPrimitiveFloat(JsonObject json, String property) { return getAsPrimitiveFloat(json.get(property)); } public static Boolean getBoolean(JsonObject json, String property) { return getAsBoolean(json.get(property)); } public static String getString(JsonObject json, String property) { return getAsString(json.get(property)); } public static String getAsString(JsonElement element) { return isNull(element) ? null : element.getAsString(); } public static Long getAsLong(JsonElement element) { return isNull(element) ? null : element.getAsLong(); } public static long getAsPrimitiveLong(JsonElement element) { Long r = getAsLong(element); return r == null ? 0L : r; } public static Integer getAsInteger(JsonElement element) { return isNull(element) ? null : element.getAsInt(); } public static int getAsPrimitiveInt(JsonElement element) { Integer r = getAsInteger(element); return r == null ? 0 : r; } public static Boolean getAsBoolean(JsonElement element) { return isNull(element) ? null : element.getAsBoolean(); } public static boolean getAsPrimitiveBool(JsonElement element) { Boolean r = getAsBoolean(element); return r != null && r; } public static Double getAsDouble(JsonElement element) { return isNull(element) ? null : element.getAsDouble(); } public static double getAsPrimitiveDouble(JsonElement element) { Double r = getAsDouble(element); return r == null ? 0d : r; } public static Float getAsFloat(JsonElement element) { return isNull(element) ? null : element.getAsFloat(); } public static float getAsPrimitiveFloat(JsonElement element) { Float r = getAsFloat(element); return r == null ? 0f : r; } public static Integer[] getIntArray(JsonObject o, String string) { JsonArray jsonArray = getAsJsonArray(o.getAsJsonArray(string)); if (jsonArray == null) { return null; } List<Integer> result = Lists.newArrayList(); for (int i = 0; i < jsonArray.size(); i++) { result.add(jsonArray.get(i).getAsInt()); } return result.toArray(new Integer[0]); } public static String[] getStringArray(JsonObject o, String string) { JsonArray jsonArray = getAsJsonArray(o.getAsJsonArray(string)); if (jsonArray == null) { return null; } List<String> result = Lists.newArrayList(); for (int i = 0; i < jsonArray.size(); i++) { result.add(jsonArray.get(i).getAsString()); } return result.toArray(new String[0]); } public static Long[] getLongArray(JsonObject o, String string) { JsonArray jsonArray = getAsJsonArray(o.getAsJsonArray(string)); if (jsonArray == null) { return null; } List<Long> result = Lists.newArrayList(); for (int i = 0; i < jsonArray.size(); i++) { result.add(jsonArray.get(i).getAsLong()); } return result.toArray(new Long[0]); } public static JsonArray getAsJsonArray(JsonElement element) { return element == null ? null : element.getAsJsonArray(); } /** * 快速构建JsonObject对象,批量添加一堆属性 * * @param keyOrValue 包含key或value的数组 * @return JsonObject对象. */ public static JsonObject buildJsonObject(Object... keyOrValue) { JsonObject result = new JsonObject(); put(result, keyOrValue); return result; } /** * 批量向JsonObject对象中添加属性 * * @param jsonObject 原始JsonObject对象 * @param keyOrValue 包含key或value的数组 */ public static void put(JsonObject jsonObject, Object... keyOrValue) { if (keyOrValue.length % 2 == 1) { throw new WxRuntimeException("参数个数必须为偶数"); } for (int i = 0; i < keyOrValue.length / 2; i++) { final Object key = keyOrValue[2 * i]; final Object value = keyOrValue[2 * i + 1]; if (value == null) { jsonObject.add(key.toString(), null); continue; } if (value instanceof Boolean) { jsonObject.addProperty(key.toString(), (Boolean) value); } else if (value instanceof Character) { jsonObject.addProperty(key.toString(), (Character) value); } else if (value instanceof Number) { jsonObject.addProperty(key.toString(), (Number) value); } else if (value instanceof JsonElement) { jsonObject.add(key.toString(), (JsonElement) value); } else if (value instanceof List) { JsonArray array = new JsonArray(); ((List<?>) value).forEach(a -> array.add(a.toString())); jsonObject.add(key.toString(), array); } else { jsonObject.add(key.toString(), WxGsonBuilder.create().toJsonTree(value)); } } } }
java
Apache-2.0
84b5c4d2d0774f800237634e5d0336f53c004fe3
2026-01-04T14:46:39.499027Z
false
binarywang/WxJava
https://github.com/binarywang/WxJava/blob/84b5c4d2d0774f800237634e5d0336f53c004fe3/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/json/WxNetCheckResultGsonAdapter.java
weixin-java-common/src/main/java/me/chanjar/weixin/common/util/json/WxNetCheckResultGsonAdapter.java
package me.chanjar.weixin.common.util.json; import com.google.gson.*; import me.chanjar.weixin.common.bean.WxNetCheckResult; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.List; /** * @author billytomato */ public class WxNetCheckResultGsonAdapter implements JsonDeserializer<WxNetCheckResult> { @Override public WxNetCheckResult deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { WxNetCheckResult result = new WxNetCheckResult(); JsonArray dnssJson = json.getAsJsonObject().get("dns").getAsJsonArray(); List<WxNetCheckResult.WxNetCheckDnsInfo> dnsInfoList = new ArrayList<>(); if (dnssJson != null && !dnssJson.isEmpty()) { for (int i = 0; i < dnssJson.size(); i++) { JsonObject buttonJson = dnssJson.get(i).getAsJsonObject(); WxNetCheckResult.WxNetCheckDnsInfo dnsInfo = new WxNetCheckResult.WxNetCheckDnsInfo(); dnsInfo.setIp(GsonHelper.getString(buttonJson, "ip")); dnsInfo.setRealOperator(GsonHelper.getString(buttonJson, "real_operator")); dnsInfoList.add(dnsInfo); } } JsonArray pingsJson = json.getAsJsonObject().get("ping").getAsJsonArray(); List<WxNetCheckResult.WxNetCheckPingInfo> pingInfoList = new ArrayList<>(); if (pingsJson != null && !pingsJson.isEmpty()) { for (int i = 0; i < pingsJson.size(); i++) { JsonObject pingJson = pingsJson.get(i).getAsJsonObject(); WxNetCheckResult.WxNetCheckPingInfo pingInfo = new WxNetCheckResult.WxNetCheckPingInfo(); pingInfo.setIp(GsonHelper.getString(pingJson, "ip")); pingInfo.setFromOperator(GsonHelper.getString(pingJson, "from_operator")); pingInfo.setPackageLoss(GsonHelper.getString(pingJson, "package_loss")); pingInfo.setTime(GsonHelper.getString(pingJson, "time")); pingInfoList.add(pingInfo); } } result.setDnsInfos(dnsInfoList); result.setPingInfos(pingInfoList); return result; } }
java
Apache-2.0
84b5c4d2d0774f800237634e5d0336f53c004fe3
2026-01-04T14:46:39.499027Z
false
binarywang/WxJava
https://github.com/binarywang/WxJava/blob/84b5c4d2d0774f800237634e5d0336f53c004fe3/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/json/WxMenuGsonAdapter.java
weixin-java-common/src/main/java/me/chanjar/weixin/common/util/json/WxMenuGsonAdapter.java
package me.chanjar.weixin.common.util.json; import com.google.gson.*; import me.chanjar.weixin.common.bean.menu.WxMenu; import me.chanjar.weixin.common.bean.menu.WxMenuButton; import me.chanjar.weixin.common.bean.menu.WxMenuRule; import java.lang.reflect.Type; import java.util.Optional; /** * @author Daniel Qian */ public class WxMenuGsonAdapter implements JsonSerializer<WxMenu>, JsonDeserializer<WxMenu> { // JSON字段常量定义 private static final String FIELD_BUTTON = "button"; private static final String FIELD_MATCH_RULE = "matchrule"; private static final String FIELD_SUB_BUTTON = "sub_button"; private static final String FIELD_MENU = "menu"; // 菜单按钮字段常量 private static final String FIELD_TYPE = "type"; private static final String FIELD_NAME = "name"; private static final String FIELD_KEY = "key"; private static final String FIELD_URL = "url"; private static final String FIELD_MEDIA_ID = "media_id"; private static final String FIELD_ARTICLE_ID = "article_id"; private static final String FIELD_APP_ID = "appid"; private static final String FIELD_PAGE_PATH = "pagepath"; // 菜单规则字段常量 private static final String FIELD_TAG_ID = "tag_id"; private static final String FIELD_SEX = "sex"; private static final String FIELD_COUNTRY = "country"; private static final String FIELD_PROVINCE = "province"; private static final String FIELD_CITY = "city"; private static final String FIELD_CLIENT_PLATFORM_TYPE = "client_platform_type"; private static final String FIELD_LANGUAGE = "language"; @Override public JsonElement serialize(WxMenu menu, Type typeOfSrc, JsonSerializationContext context) { JsonObject json = new JsonObject(); JsonArray buttonArray = new JsonArray(); Optional.ofNullable(menu.getButtons()) .ifPresent(buttons -> buttons.stream() .map(this::convertToJson) .forEach(buttonArray::add)); json.add(FIELD_BUTTON, buttonArray); if (menu.getMatchRule() != null) { json.add(FIELD_MATCH_RULE, convertToJson(menu.getMatchRule())); } return json; } protected JsonObject convertToJson(WxMenuButton button) { JsonObject buttonJson = new JsonObject(); addPropertyIfNotNull(buttonJson, FIELD_TYPE, button.getType()); addPropertyIfNotNull(buttonJson, FIELD_NAME, button.getName()); addPropertyIfNotNull(buttonJson, FIELD_KEY, button.getKey()); addPropertyIfNotNull(buttonJson, FIELD_URL, button.getUrl()); addPropertyIfNotNull(buttonJson, FIELD_MEDIA_ID, button.getMediaId()); addPropertyIfNotNull(buttonJson, FIELD_ARTICLE_ID, button.getArticleId()); addPropertyIfNotNull(buttonJson, FIELD_APP_ID, button.getAppId()); addPropertyIfNotNull(buttonJson, FIELD_PAGE_PATH, button.getPagePath()); if (button.getSubButtons() != null && !button.getSubButtons().isEmpty()) { JsonArray buttonArray = new JsonArray(); button.getSubButtons().stream() .map(this::convertToJson) .forEach(buttonArray::add); buttonJson.add(FIELD_SUB_BUTTON, buttonArray); } return buttonJson; } protected JsonObject convertToJson(WxMenuRule menuRule) { JsonObject matchRule = new JsonObject(); addPropertyIfNotNull(matchRule, FIELD_TAG_ID, menuRule.getTagId()); addPropertyIfNotNull(matchRule, FIELD_SEX, menuRule.getSex()); addPropertyIfNotNull(matchRule, FIELD_COUNTRY, menuRule.getCountry()); addPropertyIfNotNull(matchRule, FIELD_PROVINCE, menuRule.getProvince()); addPropertyIfNotNull(matchRule, FIELD_CITY, menuRule.getCity()); addPropertyIfNotNull(matchRule, FIELD_CLIENT_PLATFORM_TYPE, menuRule.getClientPlatformType()); addPropertyIfNotNull(matchRule, FIELD_LANGUAGE, menuRule.getLanguage()); return matchRule; } private void addPropertyIfNotNull(JsonObject obj, String key, String value) { if (value != null) { obj.addProperty(key, value); } } @Override public WxMenu deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { JsonObject root = json.getAsJsonObject(); JsonArray buttonsJson = null; if (root.has(FIELD_MENU)) { JsonObject menuObj = root.getAsJsonObject(FIELD_MENU); buttonsJson = menuObj.getAsJsonArray(FIELD_BUTTON); } else if (root.has(FIELD_BUTTON)) { buttonsJson = root.getAsJsonArray(FIELD_BUTTON); } if (buttonsJson == null) { throw new JsonParseException("No button array found in menu JSON"); } return buildMenuFromJson(buttonsJson); } protected WxMenu buildMenuFromJson(JsonArray buttonsJson) { WxMenu menu = new WxMenu(); for (JsonElement btnElem : buttonsJson) { JsonObject buttonJson = btnElem.getAsJsonObject(); WxMenuButton button = convertFromJson(buttonJson); menu.getButtons().add(button); if (buttonJson.has(FIELD_SUB_BUTTON) && buttonJson.get(FIELD_SUB_BUTTON).isJsonArray()) { JsonArray sub_buttonsJson = buttonJson.getAsJsonArray(FIELD_SUB_BUTTON); for (JsonElement subBtnElem : sub_buttonsJson) { button.getSubButtons().add(convertFromJson(subBtnElem.getAsJsonObject())); } } } return menu; } protected WxMenuButton convertFromJson(JsonObject json) { WxMenuButton button = new WxMenuButton(); button.setName(GsonHelper.getString(json, FIELD_NAME)); button.setKey(GsonHelper.getString(json, FIELD_KEY)); button.setUrl(GsonHelper.getString(json, FIELD_URL)); button.setType(GsonHelper.getString(json, FIELD_TYPE)); button.setMediaId(GsonHelper.getString(json, FIELD_MEDIA_ID)); button.setArticleId(GsonHelper.getString(json, FIELD_ARTICLE_ID)); button.setAppId(GsonHelper.getString(json, FIELD_APP_ID)); button.setPagePath(GsonHelper.getString(json, FIELD_PAGE_PATH)); return button; } }
java
Apache-2.0
84b5c4d2d0774f800237634e5d0336f53c004fe3
2026-01-04T14:46:39.499027Z
false
binarywang/WxJava
https://github.com/binarywang/WxJava/blob/84b5c4d2d0774f800237634e5d0336f53c004fe3/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/json/GsonParser.java
weixin-java-common/src/main/java/me/chanjar/weixin/common/util/json/GsonParser.java
package me.chanjar.weixin.common.util.json; import com.google.gson.JsonObject; import com.google.gson.JsonParser; import com.google.gson.stream.JsonReader; import java.io.Reader; /** * @author niefy */ public class GsonParser { public static JsonObject parse(String json) { return new JsonParser().parse(json).getAsJsonObject(); } public static JsonObject parse(Reader json) { return new JsonParser().parse(json).getAsJsonObject(); } public static JsonObject parse(JsonReader json) { return new JsonParser().parse(json).getAsJsonObject(); } }
java
Apache-2.0
84b5c4d2d0774f800237634e5d0336f53c004fe3
2026-01-04T14:46:39.499027Z
false
binarywang/WxJava
https://github.com/binarywang/WxJava/blob/84b5c4d2d0774f800237634e5d0336f53c004fe3/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/json/WxErrorAdapter.java
weixin-java-common/src/main/java/me/chanjar/weixin/common/util/json/WxErrorAdapter.java
package me.chanjar.weixin.common.util.json; import com.google.gson.*; import me.chanjar.weixin.common.api.WxConsts; import me.chanjar.weixin.common.error.WxError; import java.lang.reflect.Type; /** * @author Daniel Qian. */ public class WxErrorAdapter implements JsonDeserializer<WxError> { @Override public WxError deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { WxError.WxErrorBuilder errorBuilder = WxError.builder(); JsonObject wxErrorJsonObject = json.getAsJsonObject(); if (wxErrorJsonObject.get(WxConsts.ERR_CODE) != null && !wxErrorJsonObject.get(WxConsts.ERR_CODE).isJsonNull()) { errorBuilder.errorCode(GsonHelper.getAsPrimitiveInt(wxErrorJsonObject.get(WxConsts.ERR_CODE))); } if (wxErrorJsonObject.get("errmsg") != null && !wxErrorJsonObject.get("errmsg").isJsonNull()) { errorBuilder.errorMsg(GsonHelper.getAsString(wxErrorJsonObject.get("errmsg"))); } errorBuilder.json(json.toString()); return errorBuilder.build(); } }
java
Apache-2.0
84b5c4d2d0774f800237634e5d0336f53c004fe3
2026-01-04T14:46:39.499027Z
false
binarywang/WxJava
https://github.com/binarywang/WxJava/blob/84b5c4d2d0774f800237634e5d0336f53c004fe3/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/crypto/WxCryptUtil.java
weixin-java-common/src/main/java/me/chanjar/weixin/common/util/crypto/WxCryptUtil.java
package me.chanjar.weixin.common.util.crypto; import lombok.AllArgsConstructor; import lombok.Data; import me.chanjar.weixin.common.error.WxRuntimeException; import org.apache.commons.codec.binary.Base64; import org.apache.commons.lang3.StringUtils; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.xml.sax.InputSource; import javax.crypto.Cipher; import javax.crypto.spec.IvParameterSpec; import javax.crypto.spec.SecretKeySpec; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import java.io.StringReader; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import java.util.Arrays; import java.util.Random; /** * <pre> * 对公众平台发送给公众账号的消息加解密示例代码. * Copyright (c) 1998-2014 Tencent Inc. * 针对org.apache.commons.codec.binary.Base64, * 需要导入架包commons-codec-1.9(或commons-codec-1.8等其他版本) * 官方下载地址:http://commons.apache.org/proper/commons-codec/download_codec.cgi * </pre> * * @author Tencent */ public class WxCryptUtil { private static final Base64 BASE64 = new Base64(); private static final Charset CHARSET = StandardCharsets.UTF_8; private static volatile Random random; private static Random getRandom() { if (random == null) { synchronized (WxCryptUtil.class) { if (random == null) { random = new Random(); } } } return random; } private static final ThreadLocal<DocumentBuilder> BUILDER_LOCAL = ThreadLocal.withInitial(() -> { try { final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setExpandEntityReferences(false); factory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true); return factory.newDocumentBuilder(); } catch (ParserConfigurationException exc) { throw new IllegalArgumentException(exc); } }); protected byte[] aesKey; protected String token; protected String appidOrCorpid; public WxCryptUtil() { } /** * 构造函数. * * @param token 公众平台上,开发者设置的token * @param encodingAesKey 公众平台上,开发者设置的EncodingAESKey * @param appidOrCorpid 公众平台appid/corpid */ public WxCryptUtil(String token, String encodingAesKey, String appidOrCorpid) { this.token = token; this.appidOrCorpid = appidOrCorpid; this.aesKey = Base64.decodeBase64(StringUtils.remove(encodingAesKey, " ")); } private static String extractEncryptPart(String xml) { try { DocumentBuilder db = BUILDER_LOCAL.get(); Document document = db.parse(new InputSource(new StringReader(xml))); Element root = document.getDocumentElement(); return root.getElementsByTagName("Encrypt").item(0).getTextContent(); } catch (Exception e) { throw new WxRuntimeException(e); } } /** * 将一个数字转换成生成4个字节的网络字节序bytes数组. */ private static byte[] number2BytesInNetworkOrder(int number) { byte[] orderBytes = new byte[4]; orderBytes[3] = (byte) (number & 0xFF); orderBytes[2] = (byte) (number >> 8 & 0xFF); orderBytes[1] = (byte) (number >> 16 & 0xFF); orderBytes[0] = (byte) (number >> 24 & 0xFF); return orderBytes; } /** * 4个字节的网络字节序bytes数组还原成一个数字. */ private static int bytesNetworkOrder2Number(byte[] bytesInNetworkOrder) { int sourceNumber = 0; for (int i = 0; i < 4; i++) { sourceNumber <<= 8; sourceNumber |= bytesInNetworkOrder[i] & 0xff; } return sourceNumber; } /** * 随机生成16位字符串. */ private static String genRandomStr() { String base = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; Random r = getRandom(); StringBuilder sb = new StringBuilder(); for (int i = 0; i < 16; i++) { int number = r.nextInt(base.length()); sb.append(base.charAt(number)); } return sb.toString(); } /** * 生成xml消息. * * @param encrypt 加密后的消息密文 * @param signature 安全签名 * @param timestamp 时间戳 * @param nonce 随机字符串 * @return 生成的xml字符串 */ private static String generateXml(String encrypt, String signature, String timestamp, String nonce) { String format = "<xml>\n" + "<Encrypt><![CDATA[%1$s]]></Encrypt>\n" + "<MsgSignature><![CDATA[%2$s]]></MsgSignature>\n" + "<TimeStamp>%3$s</TimeStamp>\n" + "<Nonce><![CDATA[%4$s]]></Nonce>\n" + "</xml>"; return String.format(format, encrypt, signature, timestamp, nonce); } /** * 将公众平台回复用户的消息加密打包. * <ol> * <li>对要发送的消息进行AES-CBC加密</li> * <li>生成安全签名</li> * <li>将消息密文和安全签名打包成xml格式</li> * </ol> * * @param plainText 公众平台待回复用户的消息,xml格式的字符串 * @return 加密后的可以直接回复用户的密文,包括msg_signature, timestamp, nonce, encrypt的xml格式的字符串 */ public String encrypt(String plainText) { // 加密 String encryptedXml = encrypt(genRandomStr(), plainText); // 生成安全签名 String timeStamp = Long.toString(System.currentTimeMillis() / 1000L); String nonce = genRandomStr(); String signature = SHA1.gen(this.token, timeStamp, nonce, encryptedXml); return generateXml(encryptedXml, signature, timeStamp, nonce); } /** * 将公众平台回复用户的消息加密打包. * <ol> * <li>对要发送的消息进行AES-CBC加密</li> * <li>生成安全签名</li> * <li>将消息密文和安全签名打包成xml格式</li> * </ol> * * @param plainText 公众平台待回复用户的消息,xml格式的字符串 * @return 加密消息所需的值对象 */ public EncryptContext encryptContext(String plainText) { // 加密 String encryptedXml = encrypt(genRandomStr(), plainText); // 生成安全签名 String timeStamp = Long.toString(System.currentTimeMillis() / 1000L); String nonce = genRandomStr(); String signature = SHA1.gen(this.token, timeStamp, nonce, encryptedXml); return new EncryptContext(encryptedXml, signature, timeStamp, nonce); } /** * 对明文进行加密. * * @param plainText 需要加密的明文 * @return 加密后base64编码的字符串 */ public String encrypt(String randomStr, String plainText) { ByteGroup byteCollector = new ByteGroup(); byte[] randomStringBytes = randomStr.getBytes(CHARSET); byte[] plainTextBytes = plainText.getBytes(CHARSET); byte[] bytesOfSizeInNetworkOrder = number2BytesInNetworkOrder(plainTextBytes.length); byte[] appIdBytes = this.appidOrCorpid.getBytes(CHARSET); // randomStr + networkBytesOrder + text + appid byteCollector.addBytes(randomStringBytes); byteCollector.addBytes(bytesOfSizeInNetworkOrder); byteCollector.addBytes(plainTextBytes); byteCollector.addBytes(appIdBytes); // ... + pad: 使用自定义的填充方式对明文进行补位填充 byte[] padBytes = PKCS7Encoder.encode(byteCollector.size()); byteCollector.addBytes(padBytes); // 获得最终的字节流, 未加密 byte[] unencrypted = byteCollector.toBytes(); try { // 设置加密模式为AES的CBC模式 Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding"); SecretKeySpec keySpec = new SecretKeySpec(this.aesKey, "AES"); IvParameterSpec iv = new IvParameterSpec(this.aesKey, 0, 16); cipher.init(Cipher.ENCRYPT_MODE, keySpec, iv); // 加密 byte[] encrypted = cipher.doFinal(unencrypted); // 使用BASE64对加密后的字符串进行编码 return BASE64.encodeToString(encrypted); } catch (Exception e) { throw new WxRuntimeException(e); } } /** * 检验消息的真实性,并且获取解密后的明文. * <ol> * <li>利用收到的密文生成安全签名,进行签名验证</li> * <li>若验证通过,则提取xml中的加密消息</li> * <li>对消息进行解密</li> * </ol> * * @param msgSignature 签名串,对应URL参数的msg_signature * @param timeStamp 时间戳,对应URL参数的timestamp * @param nonce 随机串,对应URL参数的nonce * @param encryptedXml 包含 Encrypt 密文的 xml,对应POST请求的数据 * @return 解密后的原文 */ public String decryptXml(String msgSignature, String timeStamp, String nonce, String encryptedXml) { // 密钥,公众账号的app corpSecret // 提取密文 String cipherText = extractEncryptPart(encryptedXml); return decryptContent(msgSignature, timeStamp, nonce, cipherText); } /** * 检验消息的真实性,并且获取解密后的明文. * <ol> * <li>利用收到的密文生成安全签名,进行签名验证</li> * <li>若验证通过,则提取xml中的加密消息</li> * <li>对消息进行解密</li> * </ol> * * @param msgSignature 签名串,对应URL参数的msg_signature * @param timeStamp 时间戳,对应URL参数的timestamp * @param nonce 随机串,对应URL参数的nonce * @param encryptedXml 包含 Encrypt 密文的 xml,对应POST请求的数据 * @return 解密后的原文 * @deprecated 由于语义不清晰,置为过时方法,请查看替代方法 {@link #decryptXml} */ @Deprecated public String decrypt(String msgSignature, String timeStamp, String nonce, String encryptedXml) { return decryptXml(msgSignature, timeStamp, nonce, encryptedXml); } /** * 检验消息的真实性,并且获取解密后的明文. * <ol> * <li>利用收到的密文生成安全签名,进行签名验证</li> * <li>若验证通过,则提取xml中的加密消息</li> * <li>对消息进行解密</li> * </ol> * * @param msgSignature 签名串,对应URL参数的msg_signature * @param timeStamp 时间戳,对应URL参数的timestamp * @param nonce 随机串,对应URL参数的nonce * @param encryptedContent 加密文本体 * @return 解密后的原文 */ public String decryptContent(String msgSignature, String timeStamp, String nonce, String encryptedContent) { // 验证安全签名 String signature = SHA1.gen(this.token, timeStamp, nonce, encryptedContent); if (!signature.equals(msgSignature)) { throw new WxRuntimeException("加密消息签名校验失败"); } // 解密 return decrypt(encryptedContent); } /** * 对密文进行解密. * * @param cipherText 需要解密的密文 * @return 解密得到的明文 */ public String decrypt(String cipherText) { byte[] original; try { // 设置解密模式为AES的CBC模式 Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding"); SecretKeySpec keySpec = new SecretKeySpec(this.aesKey, "AES"); IvParameterSpec iv = new IvParameterSpec(Arrays.copyOfRange(this.aesKey, 0, 16)); cipher.init(Cipher.DECRYPT_MODE, keySpec, iv); // 使用BASE64对密文进行解码 byte[] encrypted = Base64.decodeBase64(cipherText); // 解密 original = cipher.doFinal(encrypted); } catch (Exception e) { throw new WxRuntimeException(e); } String xmlContent; String fromAppid; try { // 去除补位字符 byte[] bytes = PKCS7Encoder.decode(original); // 分离16位随机字符串,网络字节序和AppId if (bytes == null || bytes.length < 20) { throw new WxRuntimeException("解密后数据长度异常,可能为错误的密文或EncodingAESKey"); } byte[] networkOrder = Arrays.copyOfRange(bytes, 16, 20); int xmlLength = bytesNetworkOrder2Number(networkOrder); // 长度边界校验,避免非法长度导致的越界/参数异常 int startIndex = 20; int endIndex = startIndex + xmlLength; if (xmlLength < 0 || endIndex > bytes.length) { throw new WxRuntimeException("解密后数据格式非法:消息长度不正确,可能为错误的密文或EncodingAESKey"); } xmlContent = new String(Arrays.copyOfRange(bytes, startIndex, endIndex), CHARSET); fromAppid = new String(Arrays.copyOfRange(bytes, endIndex, bytes.length), CHARSET); } catch (Exception e) { if (e instanceof WxRuntimeException) { throw (WxRuntimeException) e; } else { throw new WxRuntimeException(e); } } // appid不相同的情况 暂时忽略这段判断 // if (!fromAppid.equals(this.appidOrCorpid)) { // throw new WxRuntimeException("AppID不正确,请核实!"); // } return xmlContent; } @Data @AllArgsConstructor public static class EncryptContext { private String encrypt; private String signature; private String timeStamp; private String nonce; } }
java
Apache-2.0
84b5c4d2d0774f800237634e5d0336f53c004fe3
2026-01-04T14:46:39.499027Z
false
binarywang/WxJava
https://github.com/binarywang/WxJava/blob/84b5c4d2d0774f800237634e5d0336f53c004fe3/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/crypto/SHA1.java
weixin-java-common/src/main/java/me/chanjar/weixin/common/util/crypto/SHA1.java
package me.chanjar.weixin.common.util.crypto; import org.apache.commons.codec.digest.DigestUtils; import org.apache.commons.lang3.StringUtils; import java.util.Arrays; /** * * @author Daniel Qian * created on 14/10/19 */ public class SHA1 { /** * 串接arr参数,生成sha1 digest. */ public static String gen(String... arr) { if (StringUtils.isAnyEmpty(arr)) { throw new IllegalArgumentException("非法请求参数,有部分参数为空 : " + Arrays.toString(arr)); } Arrays.sort(arr); StringBuilder sb = new StringBuilder(); for (String a : arr) { sb.append(a); } return DigestUtils.sha1Hex(sb.toString()); } /** * 用&串接arr参数,生成sha1 digest. */ public static String genWithAmple(String... arr) { if (StringUtils.isAnyEmpty(arr)) { throw new IllegalArgumentException("非法请求参数,有部分参数为空 : " + Arrays.toString(arr)); } Arrays.sort(arr); StringBuilder sb = new StringBuilder(); for (int i = 0; i < arr.length; i++) { String a = arr[i]; sb.append(a); if (i != arr.length - 1) { sb.append('&'); } } return DigestUtils.sha1Hex(sb.toString()); } }
java
Apache-2.0
84b5c4d2d0774f800237634e5d0336f53c004fe3
2026-01-04T14:46:39.499027Z
false
binarywang/WxJava
https://github.com/binarywang/WxJava/blob/84b5c4d2d0774f800237634e5d0336f53c004fe3/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/crypto/ByteGroup.java
weixin-java-common/src/main/java/me/chanjar/weixin/common/util/crypto/ByteGroup.java
package me.chanjar.weixin.common.util.crypto; import java.util.ArrayList; public class ByteGroup { ArrayList<Byte> byteContainer = new ArrayList<>(); public byte[] toBytes() { byte[] bytes = new byte[this.byteContainer.size()]; for (int i = 0; i < this.byteContainer.size(); i++) { bytes[i] = this.byteContainer.get(i); } return bytes; } public ByteGroup addBytes(byte[] bytes) { for (byte b : bytes) { this.byteContainer.add(b); } return this; } public int size() { return this.byteContainer.size(); } }
java
Apache-2.0
84b5c4d2d0774f800237634e5d0336f53c004fe3
2026-01-04T14:46:39.499027Z
false
binarywang/WxJava
https://github.com/binarywang/WxJava/blob/84b5c4d2d0774f800237634e5d0336f53c004fe3/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/crypto/PKCS7Encoder.java
weixin-java-common/src/main/java/me/chanjar/weixin/common/util/crypto/PKCS7Encoder.java
/* * 对公众平台发送给公众账号的消息加解密示例代码. * * @copyright Copyright (c) 1998-2014 Tencent Inc. */ package me.chanjar.weixin.common.util.crypto; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import java.util.Arrays; /** * 提供基于PKCS7算法的加解. * * @author tencent */ public class PKCS7Encoder { private static final Charset CHARSET = StandardCharsets.UTF_8; private static final int BLOCK_SIZE = 32; /** * 获得对明文进行补位填充的字节. * * @param count 需要进行填充补位操作的明文字节个数 * @return 补齐用的字节数组 */ public static byte[] encode(int count) { // 计算需要填充的位数 int amountToPad = BLOCK_SIZE - (count % BLOCK_SIZE); // 获得补位所用的字符 char padChr = chr(amountToPad); StringBuilder tmp = new StringBuilder(); for (int index = 0; index < amountToPad; index++) { tmp.append(padChr); } return tmp.toString().getBytes(CHARSET); } /** * 删除解密后明文的补位字符. * * @param decrypted 解密后的明文 * @return 删除补位字符后的明文 */ public static byte[] decode(byte[] decrypted) { int pad = decrypted[decrypted.length - 1]; if (pad < 1 || pad > 32) { pad = 0; } return Arrays.copyOfRange(decrypted, 0, decrypted.length - pad); } /** * 将数字转化成ASCII码对应的字符,用于对明文进行补码. * * @param a 需要转化的数字 * @return 转化得到的字符 */ private static char chr(int a) { byte target = (byte) (a & 0xFF); return (char) target; } }
java
Apache-2.0
84b5c4d2d0774f800237634e5d0336f53c004fe3
2026-01-04T14:46:39.499027Z
false
binarywang/WxJava
https://github.com/binarywang/WxJava/blob/84b5c4d2d0774f800237634e5d0336f53c004fe3/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/fs/FileUtils.java
weixin-java-common/src/main/java/me/chanjar/weixin/common/util/fs/FileUtils.java
package me.chanjar.weixin.common.util.fs; import org.apache.commons.io.IOUtils; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.nio.file.Files; import java.util.Base64; import static org.apache.commons.io.FileUtils.openOutputStream; /** * @author Daniel Qian */ public class FileUtils { /** * 创建临时文件. * * @param inputStream 输入文件流 * @param name 文件名 * @param ext 扩展名 * @param tmpDirFile 临时文件夹目录 */ public static File createTmpFile(InputStream inputStream, String name, String ext, File tmpDirFile) throws IOException { File resultFile = File.createTempFile(name, '.' + ext, tmpDirFile); resultFile.deleteOnExit(); copyToFile(inputStream, resultFile); return resultFile; } private static void copyToFile(final InputStream source, final File destination) throws IOException { try (InputStream in = source; OutputStream out = openOutputStream(destination)) { IOUtils.copy(in, out); } } /** * 创建临时文件. * * @param inputStream 输入文件流 * @param name 文件名 * @param ext 扩展名 */ public static File createTmpFile(InputStream inputStream, String name, String ext) throws IOException { return createTmpFile(inputStream, name, ext, Files.createTempDirectory("wxjava-temp").toFile()); } /** * 文件流生成base64 * * @param in 文件流 * @return base64编码 */ public static String imageToBase64ByStream(InputStream in) { byte[] data = null; // 读取图片字节数组 try { data = new byte[in.available()]; in.read(data); // 返回Base64编码过的字节数组字符串 return Base64.getEncoder().encodeToString(data); } catch (IOException e) { e.printStackTrace(); } finally { if (in != null) { try { in.close(); } catch (IOException e) { e.printStackTrace(); } } } return null; } }
java
Apache-2.0
84b5c4d2d0774f800237634e5d0336f53c004fe3
2026-01-04T14:46:39.499027Z
false
binarywang/WxJava
https://github.com/binarywang/WxJava/blob/84b5c4d2d0774f800237634e5d0336f53c004fe3/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/HttpResponseProxy.java
weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/HttpResponseProxy.java
package me.chanjar.weixin.common.util.http; import me.chanjar.weixin.common.error.WxErrorException; import me.chanjar.weixin.common.util.http.apache.ApacheHttpResponseProxy; import me.chanjar.weixin.common.util.http.hc.HttpComponentsResponseProxy; import me.chanjar.weixin.common.util.http.jodd.JoddHttpResponseProxy; import me.chanjar.weixin.common.util.http.okhttp.OkHttpResponseProxy; import java.io.UnsupportedEncodingException; import java.net.URLDecoder; import java.nio.charset.StandardCharsets; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * <pre> * http 框架的 response 代理类,方便提取公共方法 * Created by Binary Wang on 2017-8-3. * </pre> * * @author <a href="https://github.com/binarywang">Binary Wang</a> */ public interface HttpResponseProxy { static ApacheHttpResponseProxy from(org.apache.http.client.methods.CloseableHttpResponse response) { return new ApacheHttpResponseProxy(response); } static HttpComponentsResponseProxy from(org.apache.hc.client5.http.impl.classic.CloseableHttpResponse response) { return new HttpComponentsResponseProxy(response); } static JoddHttpResponseProxy from(jodd.http.HttpResponse response) { return new JoddHttpResponseProxy(response); } static OkHttpResponseProxy from(okhttp3.Response response) { return new OkHttpResponseProxy(response); } String getFileName() throws WxErrorException; static String extractFileNameFromContentString(String content) throws WxErrorException { if (content == null || content.isEmpty()) { throw new WxErrorException("无法获取到文件名,content为空"); } // 查找filename*=utf-8''开头的部分 Pattern pattern = Pattern.compile("filename\\*=utf-8''(.*?)($|;|\\s|,)"); Matcher matcher = pattern.matcher(content); if (matcher.find()) { String encodedFileName = matcher.group(1); // 解码URL编码的文件名 try { return URLDecoder.decode(encodedFileName, StandardCharsets.UTF_8.name()); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } } // 查找普通filename="..."部分 pattern = Pattern.compile("filename=\"(.*?)\""); matcher = pattern.matcher(content); if (matcher.find()) { return new String(matcher.group(1).getBytes(StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8); } throw new WxErrorException("无法获取到文件名,header信息有问题"); } }
java
Apache-2.0
84b5c4d2d0774f800237634e5d0336f53c004fe3
2026-01-04T14:46:39.499027Z
false
binarywang/WxJava
https://github.com/binarywang/WxJava/blob/84b5c4d2d0774f800237634e5d0336f53c004fe3/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/RequestHttp.java
weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/RequestHttp.java
package me.chanjar.weixin.common.util.http; /** * Created by ecoolper on 2017/4/22. * * @author ecoolper */ public interface RequestHttp<H, P> { /** * 返回httpClient. * * @return 返回httpClient */ H getRequestHttpClient(); /** * 返回httpProxy. * * @return 返回httpProxy */ P getRequestHttpProxy(); /** * 返回HttpType. * * @return HttpType */ HttpClientType getRequestType(); }
java
Apache-2.0
84b5c4d2d0774f800237634e5d0336f53c004fe3
2026-01-04T14:46:39.499027Z
false
binarywang/WxJava
https://github.com/binarywang/WxJava/blob/84b5c4d2d0774f800237634e5d0336f53c004fe3/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/ResponseHandler.java
weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/ResponseHandler.java
package me.chanjar.weixin.common.util.http; /** * <pre> * http请求响应回调处理接口. * Created by Binary Wang on 2018/12/8. * </pre> * * @param <T> 返回值类型 * @author <a href="https://github.com/binarywang">Binary Wang</a> */ public interface ResponseHandler<T> { /** * 响应结果处理. * * @param t 要处理的对象 */ void handle(T t); }
java
Apache-2.0
84b5c4d2d0774f800237634e5d0336f53c004fe3
2026-01-04T14:46:39.499027Z
false
binarywang/WxJava
https://github.com/binarywang/WxJava/blob/84b5c4d2d0774f800237634e5d0336f53c004fe3/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/URIUtil.java
weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/URIUtil.java
package me.chanjar.weixin.common.util.http; import java.nio.charset.StandardCharsets; import org.apache.commons.lang3.StringUtils; public class URIUtil { private static final String ALLOWED_CHARS = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_.!~*'()"; public static String encodeURIComponent(String input) { if (StringUtils.isEmpty(input)) { return input; } int l = input.length(); StringBuilder o = new StringBuilder(l * 3); for (int i = 0; i < l; i++) { String e = input.substring(i, i + 1); if (!ALLOWED_CHARS.contains(e)) { byte[] b = e.getBytes(StandardCharsets.UTF_8); o.append(getHex(b)); continue; } o.append(e); } return o.toString(); } private static String getHex(byte[] buf) { StringBuilder o = new StringBuilder(buf.length * 3); for (byte aBuf : buf) { int n = aBuf & 0xff; o.append("%"); if (n < 0x10) { o.append("0"); } o.append(Long.toString(n, 16).toUpperCase()); } return o.toString(); } }
java
Apache-2.0
84b5c4d2d0774f800237634e5d0336f53c004fe3
2026-01-04T14:46:39.499027Z
false
binarywang/WxJava
https://github.com/binarywang/WxJava/blob/84b5c4d2d0774f800237634e5d0336f53c004fe3/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/MinishopUploadRequestCustomizeExecutor.java
weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/MinishopUploadRequestCustomizeExecutor.java
package me.chanjar.weixin.common.util.http; import jodd.http.HttpConnectionProvider; import jodd.http.ProxyInfo; import me.chanjar.weixin.common.bean.result.WxMinishopImageUploadCustomizeResult; import me.chanjar.weixin.common.enums.WxType; import me.chanjar.weixin.common.error.WxErrorException; import me.chanjar.weixin.common.util.http.apache.ApacheMinishopMediaUploadRequestCustomizeExecutor; import me.chanjar.weixin.common.util.http.hc.HttpComponentsMinishopMediaUploadRequestCustomizeExecutor; import me.chanjar.weixin.common.util.http.jodd.JoddHttpMinishopMediaUploadRequestCustomizeExecutor; import me.chanjar.weixin.common.util.http.okhttp.OkHttpMinishopMediaUploadRequestCustomizeExecutor; import me.chanjar.weixin.common.util.http.okhttp.OkHttpProxyInfo; import okhttp3.OkHttpClient; import java.io.File; import java.io.IOException; public abstract class MinishopUploadRequestCustomizeExecutor<H, P> implements RequestExecutor<WxMinishopImageUploadCustomizeResult, File> { protected RequestHttp<H, P> requestHttp; protected String respType; protected String uploadType; protected String imgUrl; public MinishopUploadRequestCustomizeExecutor(RequestHttp<H, P> requestHttp, String respType, String imgUrl) { this.requestHttp = requestHttp; this.respType = respType; if (imgUrl == null || imgUrl.isEmpty()) { this.uploadType = "0"; } else { this.uploadType = "1"; this.imgUrl = imgUrl; } } @Override public void execute(String uri, File data, ResponseHandler<WxMinishopImageUploadCustomizeResult> handler, WxType wxType) throws WxErrorException, IOException { handler.handle(this.execute(uri, data, wxType)); } @SuppressWarnings("unchecked") public static RequestExecutor<WxMinishopImageUploadCustomizeResult, File> create(RequestHttp<?, ?> requestHttp, String respType, String imgUrl) { switch (requestHttp.getRequestType()) { case APACHE_HTTP: return new ApacheMinishopMediaUploadRequestCustomizeExecutor( (RequestHttp<org.apache.http.impl.client.CloseableHttpClient, org.apache.http.HttpHost>) requestHttp, respType, imgUrl); case JODD_HTTP: return new JoddHttpMinishopMediaUploadRequestCustomizeExecutor((RequestHttp<HttpConnectionProvider, ProxyInfo>) requestHttp, respType, imgUrl); case OK_HTTP: return new OkHttpMinishopMediaUploadRequestCustomizeExecutor((RequestHttp<OkHttpClient, OkHttpProxyInfo>) requestHttp, respType, imgUrl); case HTTP_COMPONENTS: return new HttpComponentsMinishopMediaUploadRequestCustomizeExecutor( (RequestHttp<org.apache.hc.client5.http.impl.classic.CloseableHttpClient, org.apache.hc.core5.http.HttpHost>) requestHttp, respType, imgUrl); default: throw new IllegalArgumentException("不支持的http执行器类型:" + requestHttp.getRequestType()); } } }
java
Apache-2.0
84b5c4d2d0774f800237634e5d0336f53c004fe3
2026-01-04T14:46:39.499027Z
false
binarywang/WxJava
https://github.com/binarywang/WxJava/blob/84b5c4d2d0774f800237634e5d0336f53c004fe3/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/BaseMediaDownloadRequestExecutor.java
weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/BaseMediaDownloadRequestExecutor.java
package me.chanjar.weixin.common.util.http; import jodd.http.HttpConnectionProvider; import jodd.http.ProxyInfo; import me.chanjar.weixin.common.enums.WxType; import me.chanjar.weixin.common.error.WxErrorException; import me.chanjar.weixin.common.util.http.apache.ApacheMediaDownloadRequestExecutor; import me.chanjar.weixin.common.util.http.hc.HttpComponentsMediaDownloadRequestExecutor; import me.chanjar.weixin.common.util.http.jodd.JoddHttpMediaDownloadRequestExecutor; import me.chanjar.weixin.common.util.http.okhttp.OkHttpMediaDownloadRequestExecutor; import me.chanjar.weixin.common.util.http.okhttp.OkHttpProxyInfo; import okhttp3.OkHttpClient; import java.io.File; import java.io.IOException; /** * 下载媒体文件请求执行器. * 请求的参数是String, 返回的结果是File * 视频文件不支持下载 * * @author Daniel Qian */ public abstract class BaseMediaDownloadRequestExecutor<H, P> implements RequestExecutor<File, String> { protected RequestHttp<H, P> requestHttp; protected File tmpDirFile; public BaseMediaDownloadRequestExecutor(RequestHttp<H, P> requestHttp, File tmpDirFile) { this.requestHttp = requestHttp; this.tmpDirFile = tmpDirFile; } @Override public void execute(String uri, String data, ResponseHandler<File> handler, WxType wxType) throws WxErrorException, IOException { handler.handle(this.execute(uri, data, wxType)); } @SuppressWarnings("unchecked") public static RequestExecutor<File, String> create(RequestHttp<?, ?> requestHttp, File tmpDirFile) { switch (requestHttp.getRequestType()) { case APACHE_HTTP: return new ApacheMediaDownloadRequestExecutor( (RequestHttp<org.apache.http.impl.client.CloseableHttpClient, org.apache.http.HttpHost>) requestHttp, tmpDirFile); case JODD_HTTP: return new JoddHttpMediaDownloadRequestExecutor((RequestHttp<HttpConnectionProvider, ProxyInfo>) requestHttp, tmpDirFile); case OK_HTTP: return new OkHttpMediaDownloadRequestExecutor((RequestHttp<OkHttpClient, OkHttpProxyInfo>) requestHttp, tmpDirFile); case HTTP_COMPONENTS: return new HttpComponentsMediaDownloadRequestExecutor( (RequestHttp<org.apache.hc.client5.http.impl.classic.CloseableHttpClient, org.apache.hc.core5.http.HttpHost>) requestHttp, tmpDirFile); default: throw new IllegalArgumentException("不支持的http执行器类型:" + requestHttp.getRequestType()); } } }
java
Apache-2.0
84b5c4d2d0774f800237634e5d0336f53c004fe3
2026-01-04T14:46:39.499027Z
false
binarywang/WxJava
https://github.com/binarywang/WxJava/blob/84b5c4d2d0774f800237634e5d0336f53c004fe3/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/HttpClientType.java
weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/HttpClientType.java
package me.chanjar.weixin.common.util.http; /** * Created by ecoolper on 2017/4/28. */ public enum HttpClientType { /** * jodd-http. */ JODD_HTTP, /** * apache httpclient 4.x. */ APACHE_HTTP, /** * okhttp. */ OK_HTTP, /** * apache httpclient 5.x. */ HTTP_COMPONENTS }
java
Apache-2.0
84b5c4d2d0774f800237634e5d0336f53c004fe3
2026-01-04T14:46:39.499027Z
false
binarywang/WxJava
https://github.com/binarywang/WxJava/blob/84b5c4d2d0774f800237634e5d0336f53c004fe3/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/MediaUploadRequestExecutor.java
weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/MediaUploadRequestExecutor.java
package me.chanjar.weixin.common.util.http; import jodd.http.HttpConnectionProvider; import jodd.http.ProxyInfo; import me.chanjar.weixin.common.bean.CommonUploadParam; import me.chanjar.weixin.common.bean.result.WxMediaUploadResult; import me.chanjar.weixin.common.enums.WxType; import me.chanjar.weixin.common.error.WxErrorException; import me.chanjar.weixin.common.service.WxService; import me.chanjar.weixin.common.util.http.apache.ApacheMediaUploadRequestExecutor; import me.chanjar.weixin.common.util.http.hc.HttpComponentsMediaUploadRequestExecutor; import me.chanjar.weixin.common.util.http.jodd.JoddHttpMediaUploadRequestExecutor; import me.chanjar.weixin.common.util.http.okhttp.OkHttpMediaUploadRequestExecutor; import me.chanjar.weixin.common.util.http.okhttp.OkHttpProxyInfo; import okhttp3.OkHttpClient; import java.io.File; import java.io.IOException; /** * 上传媒体文件请求执行器. * 请求的参数是File, 返回的结果是String * * @author Daniel Qian * @see WxService#upload(String, CommonUploadParam) 通用的上传,封装接口是推荐调用此方法 * @see CommonUploadParam 通用的上传参数 * @deprecated 不应该继续使用执行器的方式上传文件,封装上传接口时应调用通用的文件上传,而旧代码也应该逐步迁移为新的上传方式 */ @Deprecated public abstract class MediaUploadRequestExecutor<H, P> implements RequestExecutor<WxMediaUploadResult, File> { protected RequestHttp<H, P> requestHttp; public MediaUploadRequestExecutor(RequestHttp<H, P> requestHttp) { this.requestHttp = requestHttp; } @Override public void execute(String uri, File data, ResponseHandler<WxMediaUploadResult> handler, WxType wxType) throws WxErrorException, IOException { handler.handle(this.execute(uri, data, wxType)); } @SuppressWarnings("unchecked") public static RequestExecutor<WxMediaUploadResult, File> create(RequestHttp<?, ?> requestHttp) { switch (requestHttp.getRequestType()) { case APACHE_HTTP: return new ApacheMediaUploadRequestExecutor( (RequestHttp<org.apache.http.impl.client.CloseableHttpClient, org.apache.http.HttpHost>) requestHttp); case JODD_HTTP: return new JoddHttpMediaUploadRequestExecutor((RequestHttp<HttpConnectionProvider, ProxyInfo>) requestHttp); case OK_HTTP: return new OkHttpMediaUploadRequestExecutor((RequestHttp<OkHttpClient, OkHttpProxyInfo>) requestHttp); case HTTP_COMPONENTS: return new HttpComponentsMediaUploadRequestExecutor( (RequestHttp<org.apache.hc.client5.http.impl.classic.CloseableHttpClient, org.apache.hc.core5.http.HttpHost>) requestHttp); default: throw new IllegalArgumentException("不支持的http执行器类型:" + requestHttp.getRequestType()); } } }
java
Apache-2.0
84b5c4d2d0774f800237634e5d0336f53c004fe3
2026-01-04T14:46:39.499027Z
false
binarywang/WxJava
https://github.com/binarywang/WxJava/blob/84b5c4d2d0774f800237634e5d0336f53c004fe3/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/MinishopUploadRequestExecutor.java
weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/MinishopUploadRequestExecutor.java
package me.chanjar.weixin.common.util.http; import jodd.http.HttpConnectionProvider; import jodd.http.ProxyInfo; import me.chanjar.weixin.common.bean.result.WxMinishopImageUploadResult; import me.chanjar.weixin.common.enums.WxType; import me.chanjar.weixin.common.error.WxErrorException; import me.chanjar.weixin.common.util.http.apache.ApacheMinishopMediaUploadRequestExecutor; import me.chanjar.weixin.common.util.http.hc.HttpComponentsMinishopMediaUploadRequestExecutor; import me.chanjar.weixin.common.util.http.jodd.JoddHttpMinishopMediaUploadRequestExecutor; import me.chanjar.weixin.common.util.http.okhttp.OkHttpMinishopMediaUploadRequestExecutor; import me.chanjar.weixin.common.util.http.okhttp.OkHttpProxyInfo; import okhttp3.OkHttpClient; import java.io.File; import java.io.IOException; public abstract class MinishopUploadRequestExecutor<H, P> implements RequestExecutor<WxMinishopImageUploadResult, File> { protected RequestHttp<H, P> requestHttp; public MinishopUploadRequestExecutor(RequestHttp<H, P> requestHttp) { this.requestHttp = requestHttp; } @Override public void execute(String uri, File data, ResponseHandler<WxMinishopImageUploadResult> handler, WxType wxType) throws WxErrorException, IOException { handler.handle(this.execute(uri, data, wxType)); } @SuppressWarnings("unchecked") public static RequestExecutor<WxMinishopImageUploadResult, File> create(RequestHttp<?, ?> requestHttp) { switch (requestHttp.getRequestType()) { case APACHE_HTTP: return new ApacheMinishopMediaUploadRequestExecutor( (RequestHttp<org.apache.http.impl.client.CloseableHttpClient, org.apache.http.HttpHost>) requestHttp); case JODD_HTTP: return new JoddHttpMinishopMediaUploadRequestExecutor((RequestHttp<HttpConnectionProvider, ProxyInfo>) requestHttp); case OK_HTTP: return new OkHttpMinishopMediaUploadRequestExecutor((RequestHttp<OkHttpClient, OkHttpProxyInfo>) requestHttp); case HTTP_COMPONENTS: return new HttpComponentsMinishopMediaUploadRequestExecutor( (RequestHttp<org.apache.hc.client5.http.impl.classic.CloseableHttpClient, org.apache.hc.core5.http.HttpHost>) requestHttp); default: throw new IllegalArgumentException("不支持的http执行器类型:" + requestHttp.getRequestType()); } } }
java
Apache-2.0
84b5c4d2d0774f800237634e5d0336f53c004fe3
2026-01-04T14:46:39.499027Z
false
binarywang/WxJava
https://github.com/binarywang/WxJava/blob/84b5c4d2d0774f800237634e5d0336f53c004fe3/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/SimpleGetRequestExecutor.java
weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/SimpleGetRequestExecutor.java
package me.chanjar.weixin.common.util.http; import jodd.http.HttpConnectionProvider; import jodd.http.ProxyInfo; import me.chanjar.weixin.common.enums.WxType; import me.chanjar.weixin.common.error.WxError; import me.chanjar.weixin.common.error.WxErrorException; import me.chanjar.weixin.common.util.http.apache.ApacheSimpleGetRequestExecutor; import me.chanjar.weixin.common.util.http.hc.HttpComponentsSimpleGetRequestExecutor; import me.chanjar.weixin.common.util.http.jodd.JoddHttpSimpleGetRequestExecutor; import me.chanjar.weixin.common.util.http.okhttp.OkHttpProxyInfo; import me.chanjar.weixin.common.util.http.okhttp.OkHttpSimpleGetRequestExecutor; import okhttp3.OkHttpClient; import java.io.IOException; /** * 简单的GET请求执行器. * 请求的参数是String, 返回的结果也是String * * @author Daniel Qian */ public abstract class SimpleGetRequestExecutor<H, P> implements RequestExecutor<String, String> { protected RequestHttp<H, P> requestHttp; public SimpleGetRequestExecutor(RequestHttp<H, P> requestHttp) { this.requestHttp = requestHttp; } @Override public void execute(String uri, String data, ResponseHandler<String> handler, WxType wxType) throws WxErrorException, IOException { handler.handle(this.execute(uri, data, wxType)); } @SuppressWarnings("unchecked") public static RequestExecutor<String, String> create(RequestHttp<?, ?> requestHttp) { switch (requestHttp.getRequestType()) { case APACHE_HTTP: return new ApacheSimpleGetRequestExecutor( (RequestHttp<org.apache.http.impl.client.CloseableHttpClient, org.apache.http.HttpHost>) requestHttp); case JODD_HTTP: return new JoddHttpSimpleGetRequestExecutor((RequestHttp<HttpConnectionProvider, ProxyInfo>) requestHttp); case OK_HTTP: return new OkHttpSimpleGetRequestExecutor((RequestHttp<OkHttpClient, OkHttpProxyInfo>) requestHttp); case HTTP_COMPONENTS: return new HttpComponentsSimpleGetRequestExecutor( (RequestHttp<org.apache.hc.client5.http.impl.classic.CloseableHttpClient, org.apache.hc.core5.http.HttpHost>) requestHttp); default: throw new IllegalArgumentException("不支持的http执行器类型:" + requestHttp.getRequestType()); } } protected String handleResponse(WxType wxType, String responseContent) throws WxErrorException { WxError error = WxError.fromJson(responseContent, wxType); if (error.getErrorCode() != 0) { throw new WxErrorException(error); } return responseContent; } }
java
Apache-2.0
84b5c4d2d0774f800237634e5d0336f53c004fe3
2026-01-04T14:46:39.499027Z
false
binarywang/WxJava
https://github.com/binarywang/WxJava/blob/84b5c4d2d0774f800237634e5d0336f53c004fe3/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/RequestExecutor.java
weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/RequestExecutor.java
package me.chanjar.weixin.common.util.http; import me.chanjar.weixin.common.enums.WxType; import me.chanjar.weixin.common.error.WxErrorException; import java.io.IOException; /** * http请求执行器. * * @param <T> 返回值类型 * @param <E> 请求参数类型 * @author Daniel Qian */ public interface RequestExecutor<T, E> { /** * 执行http请求. * * @param uri uri * @param data 数据 * @param wxType 微信模块类型 * @return 响应结果 * @throws WxErrorException 自定义异常 * @throws IOException io异常 */ T execute(String uri, E data, WxType wxType) throws WxErrorException, IOException; /** * 执行http请求. * * @param uri uri * @param data 数据 * @param handler http响应处理器 * @param wxType 微信模块类型 * @throws WxErrorException 自定义异常 * @throws IOException io异常 */ void execute(String uri, E data, ResponseHandler<T> handler, WxType wxType) throws WxErrorException, IOException; }
java
Apache-2.0
84b5c4d2d0774f800237634e5d0336f53c004fe3
2026-01-04T14:46:39.499027Z
false
binarywang/WxJava
https://github.com/binarywang/WxJava/blob/84b5c4d2d0774f800237634e5d0336f53c004fe3/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/WxDnsResolver.java
weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/WxDnsResolver.java
package me.chanjar.weixin.common.util.http; import org.apache.http.conn.DnsResolver; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.net.InetAddress; import java.net.UnknownHostException; import java.util.HashMap; import java.util.Map; /** * 微信DNS域名解析器,将微信域名绑定到指定IP * -------------------------------------------- * 适用于服务器端调用微信服务器需要开通出口防火墙情况 * <p> * Created by Andy Huo on 17/03/28. */ public class WxDnsResolver implements DnsResolver { private static final String WECHAT_API_URL = "api.weixin.qq.com"; private static Map<String, InetAddress[]> MAPPINGS = new HashMap<>(); protected final Logger log = LoggerFactory.getLogger(WxDnsResolver.class); private String wxApiIp; public WxDnsResolver(String ip) { this.wxApiIp = ip; this.init(); } private void init() { if (log.isDebugEnabled()) { log.debug("init wechat dns config with ip {}", wxApiIp); } try { MAPPINGS.put(WECHAT_API_URL, new InetAddress[]{InetAddress.getByName(wxApiIp)}); } catch (UnknownHostException e) { //如果初始化DNS配置失败则使用默认配置,不影响服务的启动 log.error("init WxDnsResolver error", e); MAPPINGS = new HashMap<>(); } } @Override public InetAddress[] resolve(String host) throws UnknownHostException { return MAPPINGS.containsKey(host) ? MAPPINGS.get(host) : new InetAddress[0]; } public String getWxApiIp() { return wxApiIp; } public void setWxApiIp(String wxApiIp) { this.wxApiIp = wxApiIp; this.init(); } }
java
Apache-2.0
84b5c4d2d0774f800237634e5d0336f53c004fe3
2026-01-04T14:46:39.499027Z
false
binarywang/WxJava
https://github.com/binarywang/WxJava/blob/84b5c4d2d0774f800237634e5d0336f53c004fe3/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/MediaInputStreamUploadRequestExecutor.java
weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/MediaInputStreamUploadRequestExecutor.java
package me.chanjar.weixin.common.util.http; import jodd.http.HttpConnectionProvider; import jodd.http.ProxyInfo; import me.chanjar.weixin.common.bean.result.WxMediaUploadResult; import me.chanjar.weixin.common.enums.WxType; import me.chanjar.weixin.common.error.WxErrorException; import me.chanjar.weixin.common.util.http.apache.ApacheMediaInputStreamUploadRequestExecutor; import me.chanjar.weixin.common.util.http.hc.HttpComponentsMediaInputStreamUploadRequestExecutor; import me.chanjar.weixin.common.util.http.jodd.JoddHttpMediaInputStreamUploadRequestExecutor; import me.chanjar.weixin.common.util.http.okhttp.OkHttpMediaInputStreamUploadRequestExecutor; import me.chanjar.weixin.common.util.http.okhttp.OkHttpProxyInfo; import okhttp3.OkHttpClient; import java.io.IOException; /** * 上传媒体文件请求执行器. * 请求的参数是File, 返回的结果是String * * @author Daniel Qian */ public abstract class MediaInputStreamUploadRequestExecutor<H, P> implements RequestExecutor<WxMediaUploadResult, InputStreamData> { protected RequestHttp<H, P> requestHttp; public MediaInputStreamUploadRequestExecutor(RequestHttp<H, P> requestHttp) { this.requestHttp = requestHttp; } @Override public void execute(String uri, InputStreamData data, ResponseHandler<WxMediaUploadResult> handler, WxType wxType) throws WxErrorException, IOException { handler.handle(this.execute(uri, data, wxType)); } @SuppressWarnings("unchecked") public static RequestExecutor<WxMediaUploadResult, InputStreamData> create(RequestHttp<?, ?> requestHttp) { switch (requestHttp.getRequestType()) { case APACHE_HTTP: return new ApacheMediaInputStreamUploadRequestExecutor( (RequestHttp<org.apache.http.impl.client.CloseableHttpClient, org.apache.http.HttpHost>) requestHttp); case JODD_HTTP: return new JoddHttpMediaInputStreamUploadRequestExecutor((RequestHttp<HttpConnectionProvider, ProxyInfo>) requestHttp); case OK_HTTP: return new OkHttpMediaInputStreamUploadRequestExecutor((RequestHttp<OkHttpClient, OkHttpProxyInfo>) requestHttp); case HTTP_COMPONENTS: return new HttpComponentsMediaInputStreamUploadRequestExecutor( (RequestHttp<org.apache.hc.client5.http.impl.classic.CloseableHttpClient, org.apache.hc.core5.http.HttpHost>) requestHttp); default: throw new IllegalArgumentException("不支持的http执行器类型:" + requestHttp.getRequestType()); } } }
java
Apache-2.0
84b5c4d2d0774f800237634e5d0336f53c004fe3
2026-01-04T14:46:39.499027Z
false
binarywang/WxJava
https://github.com/binarywang/WxJava/blob/84b5c4d2d0774f800237634e5d0336f53c004fe3/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/InputStreamData.java
weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/InputStreamData.java
package me.chanjar.weixin.common.util.http; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import lombok.experimental.Accessors; import java.io.InputStream; import java.io.Serializable; /** * 输入流数据. * <p/> * InputStreamData * * @author zichuan.zhou91@gmail.com * created on 2022/2/15 */ @Data @Accessors(chain = true) @NoArgsConstructor @AllArgsConstructor public class InputStreamData implements Serializable { private static final long serialVersionUID = -4627006604779378520L; private InputStream inputStream; private String filename; }
java
Apache-2.0
84b5c4d2d0774f800237634e5d0336f53c004fe3
2026-01-04T14:46:39.499027Z
false
binarywang/WxJava
https://github.com/binarywang/WxJava/blob/84b5c4d2d0774f800237634e5d0336f53c004fe3/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/SimplePostRequestExecutor.java
weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/SimplePostRequestExecutor.java
package me.chanjar.weixin.common.util.http; import jodd.http.HttpConnectionProvider; import jodd.http.ProxyInfo; import me.chanjar.weixin.common.enums.WxType; import me.chanjar.weixin.common.error.WxError; import me.chanjar.weixin.common.error.WxErrorException; import me.chanjar.weixin.common.util.http.apache.ApacheSimplePostRequestExecutor; import me.chanjar.weixin.common.util.http.hc.HttpComponentsSimplePostRequestExecutor; import me.chanjar.weixin.common.util.http.jodd.JoddHttpSimplePostRequestExecutor; import me.chanjar.weixin.common.util.http.okhttp.OkHttpProxyInfo; import me.chanjar.weixin.common.util.http.okhttp.OkHttpSimplePostRequestExecutor; import okhttp3.OkHttpClient; import org.jetbrains.annotations.NotNull; import java.io.IOException; /** * 简单的POST请求执行器,请求的参数是String, 返回的结果也是String * * @author Daniel Qian */ public abstract class SimplePostRequestExecutor<H, P> implements RequestExecutor<String, String> { protected RequestHttp<H, P> requestHttp; public SimplePostRequestExecutor(RequestHttp<H, P> requestHttp) { this.requestHttp = requestHttp; } @Override public void execute(String uri, String data, ResponseHandler<String> handler, WxType wxType) throws WxErrorException, IOException { handler.handle(this.execute(uri, data, wxType)); } @SuppressWarnings("unchecked") public static RequestExecutor<String, String> create(RequestHttp<?, ?> requestHttp) { switch (requestHttp.getRequestType()) { case APACHE_HTTP: return new ApacheSimplePostRequestExecutor( (RequestHttp<org.apache.http.impl.client.CloseableHttpClient, org.apache.http.HttpHost>) requestHttp); case JODD_HTTP: return new JoddHttpSimplePostRequestExecutor((RequestHttp<HttpConnectionProvider, ProxyInfo>) requestHttp); case OK_HTTP: return new OkHttpSimplePostRequestExecutor((RequestHttp<OkHttpClient, OkHttpProxyInfo>) requestHttp); case HTTP_COMPONENTS: return new HttpComponentsSimplePostRequestExecutor( (RequestHttp<org.apache.hc.client5.http.impl.classic.CloseableHttpClient, org.apache.hc.core5.http.HttpHost>) requestHttp); default: throw new IllegalArgumentException("不支持的http执行器类型:" + requestHttp.getRequestType()); } } @NotNull public String handleResponse(WxType wxType, String responseContent) throws WxErrorException { if (responseContent.isEmpty()) { throw new WxErrorException("无响应内容"); } if (responseContent.startsWith("<xml>")) { //xml格式输出直接返回 return responseContent; } WxError error = WxError.fromJson(responseContent, wxType); if (error.getErrorCode() != 0) { throw new WxErrorException(error); } return responseContent; } }
java
Apache-2.0
84b5c4d2d0774f800237634e5d0336f53c004fe3
2026-01-04T14:46:39.499027Z
false
binarywang/WxJava
https://github.com/binarywang/WxJava/blob/84b5c4d2d0774f800237634e5d0336f53c004fe3/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/apache/ApacheSimpleGetRequestExecutor.java
weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/apache/ApacheSimpleGetRequestExecutor.java
package me.chanjar.weixin.common.util.http.apache; import me.chanjar.weixin.common.enums.WxType; import me.chanjar.weixin.common.error.WxErrorException; import me.chanjar.weixin.common.util.http.RequestHttp; import me.chanjar.weixin.common.util.http.SimpleGetRequestExecutor; import org.apache.http.HttpHost; import org.apache.http.client.config.RequestConfig; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.CloseableHttpClient; import java.io.IOException; /** * . * * @author ecoolper * created on 2017/5/4 */ public class ApacheSimpleGetRequestExecutor extends SimpleGetRequestExecutor<CloseableHttpClient, HttpHost> { public ApacheSimpleGetRequestExecutor(RequestHttp<CloseableHttpClient, HttpHost> requestHttp) { super(requestHttp); } @Override public String execute(String uri, String queryParam, WxType wxType) throws WxErrorException, IOException { if (queryParam != null) { if (uri.indexOf('?') == -1) { uri += '?'; } uri += uri.endsWith("?") ? queryParam : '&' + queryParam; } HttpGet httpGet = new HttpGet(uri); if (requestHttp.getRequestHttpProxy() != null) { RequestConfig config = RequestConfig.custom().setProxy(requestHttp.getRequestHttpProxy()).build(); httpGet.setConfig(config); } String responseContent = requestHttp.getRequestHttpClient().execute(httpGet, Utf8ResponseHandler.INSTANCE); return handleResponse(wxType, responseContent); } }
java
Apache-2.0
84b5c4d2d0774f800237634e5d0336f53c004fe3
2026-01-04T14:46:39.499027Z
false
binarywang/WxJava
https://github.com/binarywang/WxJava/blob/84b5c4d2d0774f800237634e5d0336f53c004fe3/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/apache/ApacheMediaUploadRequestExecutor.java
weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/apache/ApacheMediaUploadRequestExecutor.java
package me.chanjar.weixin.common.util.http.apache; import me.chanjar.weixin.common.bean.result.WxMediaUploadResult; import me.chanjar.weixin.common.enums.WxType; import me.chanjar.weixin.common.error.WxError; import me.chanjar.weixin.common.error.WxErrorException; import me.chanjar.weixin.common.util.http.MediaUploadRequestExecutor; import me.chanjar.weixin.common.util.http.RequestHttp; import org.apache.http.HttpEntity; import org.apache.http.HttpHost; import org.apache.http.client.config.RequestConfig; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.mime.HttpMultipartMode; import org.apache.http.entity.mime.MultipartEntityBuilder; import org.apache.http.impl.client.CloseableHttpClient; import java.io.File; import java.io.IOException; /** * Created by ecoolper on 2017/5/5. */ public class ApacheMediaUploadRequestExecutor extends MediaUploadRequestExecutor<CloseableHttpClient, HttpHost> { public ApacheMediaUploadRequestExecutor(RequestHttp<CloseableHttpClient, HttpHost> requestHttp) { super(requestHttp); } @Override public WxMediaUploadResult execute(String uri, File file, WxType wxType) throws WxErrorException, IOException { HttpPost httpPost = new HttpPost(uri); if (requestHttp.getRequestHttpProxy() != null) { RequestConfig config = RequestConfig.custom().setProxy(requestHttp.getRequestHttpProxy()).build(); httpPost.setConfig(config); } if (file != null) { HttpEntity entity = MultipartEntityBuilder .create() .addBinaryBody("media", file) .setMode(HttpMultipartMode.RFC6532) .build(); httpPost.setEntity(entity); } String responseContent = requestHttp.getRequestHttpClient().execute(httpPost, Utf8ResponseHandler.INSTANCE); WxError error = WxError.fromJson(responseContent, wxType); if (error.getErrorCode() != 0) { throw new WxErrorException(error); } return WxMediaUploadResult.fromJson(responseContent); } }
java
Apache-2.0
84b5c4d2d0774f800237634e5d0336f53c004fe3
2026-01-04T14:46:39.499027Z
false
binarywang/WxJava
https://github.com/binarywang/WxJava/blob/84b5c4d2d0774f800237634e5d0336f53c004fe3/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/apache/ApacheMinishopMediaUploadRequestCustomizeExecutor.java
weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/apache/ApacheMinishopMediaUploadRequestCustomizeExecutor.java
package me.chanjar.weixin.common.util.http.apache; import lombok.extern.slf4j.Slf4j; import me.chanjar.weixin.common.bean.result.WxMinishopImageUploadCustomizeResult; import me.chanjar.weixin.common.enums.WxType; import me.chanjar.weixin.common.error.WxError; import me.chanjar.weixin.common.error.WxErrorException; import me.chanjar.weixin.common.util.http.MinishopUploadRequestCustomizeExecutor; import me.chanjar.weixin.common.util.http.RequestHttp; import org.apache.http.HttpEntity; import org.apache.http.HttpHost; import org.apache.http.client.config.RequestConfig; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.mime.HttpMultipartMode; import org.apache.http.entity.mime.MultipartEntityBuilder; import org.apache.http.impl.client.CloseableHttpClient; import java.io.File; import java.io.IOException; /** * Created by liming1019 on 2021/8/10. */ @Slf4j public class ApacheMinishopMediaUploadRequestCustomizeExecutor extends MinishopUploadRequestCustomizeExecutor<CloseableHttpClient, HttpHost> { public ApacheMinishopMediaUploadRequestCustomizeExecutor(RequestHttp<CloseableHttpClient, HttpHost> requestHttp, String respType, String imgUrl) { super(requestHttp, respType, imgUrl); } @Override public WxMinishopImageUploadCustomizeResult execute(String uri, File file, WxType wxType) throws WxErrorException, IOException { HttpPost httpPost = new HttpPost(uri); if (requestHttp.getRequestHttpProxy() != null) { RequestConfig config = RequestConfig.custom().setProxy(requestHttp.getRequestHttpProxy()).build(); httpPost.setConfig(config); } if (this.uploadType.equals("0")) { if (file == null) { throw new WxErrorException("上传文件为空"); } HttpEntity entity = MultipartEntityBuilder .create() .addBinaryBody("media", file) .addTextBody("resp_type", this.respType) .addTextBody("upload_type", this.uploadType) .setMode(HttpMultipartMode.RFC6532) .build(); httpPost.setEntity(entity); } else { HttpEntity entity = MultipartEntityBuilder .create() .addTextBody("resp_type", this.respType) .addTextBody("upload_type", this.uploadType) .addTextBody("img_url", this.imgUrl) .setMode(HttpMultipartMode.RFC6532) .build(); httpPost.setEntity(entity); } String responseContent = requestHttp.getRequestHttpClient().execute(httpPost, Utf8ResponseHandler.INSTANCE); WxError error = WxError.fromJson(responseContent, wxType); if (error.getErrorCode() != 0) { throw new WxErrorException(error); } log.info("responseContent: {}", responseContent); return WxMinishopImageUploadCustomizeResult.fromJson(responseContent); } }
java
Apache-2.0
84b5c4d2d0774f800237634e5d0336f53c004fe3
2026-01-04T14:46:39.499027Z
false
binarywang/WxJava
https://github.com/binarywang/WxJava/blob/84b5c4d2d0774f800237634e5d0336f53c004fe3/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/apache/ApacheBasicResponseHandler.java
weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/apache/ApacheBasicResponseHandler.java
package me.chanjar.weixin.common.util.http.apache; import org.apache.http.impl.client.BasicResponseHandler; public class ApacheBasicResponseHandler extends BasicResponseHandler { public static final ApacheBasicResponseHandler INSTANCE = new ApacheBasicResponseHandler(); }
java
Apache-2.0
84b5c4d2d0774f800237634e5d0336f53c004fe3
2026-01-04T14:46:39.499027Z
false
binarywang/WxJava
https://github.com/binarywang/WxJava/blob/84b5c4d2d0774f800237634e5d0336f53c004fe3/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/apache/ByteArrayResponseHandler.java
weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/apache/ByteArrayResponseHandler.java
package me.chanjar.weixin.common.util.http.apache; import org.apache.http.HttpEntity; import org.apache.http.impl.client.AbstractResponseHandler; import org.apache.http.util.EntityUtils; import java.io.IOException; public class ByteArrayResponseHandler extends AbstractResponseHandler<byte[]> { public static final ByteArrayResponseHandler INSTANCE = new ByteArrayResponseHandler(); @Override public byte[] handleEntity(HttpEntity entity) throws IOException { return EntityUtils.toByteArray(entity); } }
java
Apache-2.0
84b5c4d2d0774f800237634e5d0336f53c004fe3
2026-01-04T14:46:39.499027Z
false
binarywang/WxJava
https://github.com/binarywang/WxJava/blob/84b5c4d2d0774f800237634e5d0336f53c004fe3/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/apache/DefaultApacheHttpClientBuilder.java
weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/apache/DefaultApacheHttpClientBuilder.java
package me.chanjar.weixin.common.util.http.apache; import lombok.Data; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.StringUtils; import org.apache.http.HttpHost; import org.apache.http.HttpRequestInterceptor; import org.apache.http.HttpResponseInterceptor; import org.apache.http.auth.AuthScope; import org.apache.http.auth.UsernamePasswordCredentials; import org.apache.http.client.CredentialsProvider; import org.apache.http.client.HttpRequestRetryHandler; import org.apache.http.client.config.RequestConfig; import org.apache.http.config.Registry; import org.apache.http.config.RegistryBuilder; import org.apache.http.config.SocketConfig; import org.apache.http.conn.ConnectionKeepAliveStrategy; import org.apache.http.conn.HttpClientConnectionManager; import org.apache.http.conn.socket.ConnectionSocketFactory; import org.apache.http.conn.socket.PlainConnectionSocketFactory; import org.apache.http.conn.ssl.SSLConnectionSocketFactory; import org.apache.http.conn.ssl.TrustStrategy; import org.apache.http.impl.client.BasicCredentialsProvider; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.impl.client.HttpClients; import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; import org.apache.http.ssl.SSLContexts; import javax.annotation.concurrent.NotThreadSafe; import javax.net.ssl.SSLContext; import java.security.KeyManagementException; import java.security.KeyStoreException; import java.security.NoSuchAlgorithmException; import java.util.ArrayList; import java.util.List; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; /** * httpclient 连接管理器 * * @author kakotor */ @Slf4j @Data @NotThreadSafe public class DefaultApacheHttpClientBuilder implements ApacheHttpClientBuilder { private final AtomicBoolean prepared = new AtomicBoolean(false); /** * 获取链接的超时时间设置 * <p> * 设置为零时不超时,一直等待. * 设置为负数是使用系统默认设置(非3000ms的默认值,而是httpClient的默认设置). * </p> */ private int connectionRequestTimeout = 3000; /** * 建立链接的超时时间,默认为5000ms.由于是在链接池获取链接,此设置应该并不起什么作用 * <p> * 设置为零时不超时,一直等待. * 设置为负数是使用系统默认设置(非上述的5000ms的默认值,而是httpclient的默认设置). * </p> */ private int connectionTimeout = 5000; /** * 默认NIO的socket超时设置,默认5000ms. */ private int soTimeout = 5000; /** * 空闲链接的超时时间,默认60000ms. * <p> * 超时的链接将在下一次空闲链接检查是被销毁 * </p> */ private int idleConnTimeout = 60000; /** * 检查空间链接的间隔周期,默认60000ms. */ private int checkWaitTime = 60000; /** * 每路的最大链接数,默认10 */ private int maxConnPerHost = 10; /** * 最大总连接数,默认50 */ private int maxTotalConn = 50; /** * 自定义httpclient的User Agent */ private String userAgent; /** * 支持的TLS协议版本,默认支持现代TLS版本 * Supported TLS protocol versions, defaults to modern TLS versions */ private String[] supportedProtocols = {"TLSv1.2", "TLSv1.3", "TLSv1.1", "TLSv1"}; /** * 自定义请求拦截器 */ private List<HttpRequestInterceptor> requestInterceptors = new ArrayList<>(); /** * 自定义响应拦截器 */ private List<HttpResponseInterceptor> responseInterceptors = new ArrayList<>(); /** * 自定义重试策略 */ private HttpRequestRetryHandler httpRequestRetryHandler; /** * 自定义KeepAlive策略 */ private ConnectionKeepAliveStrategy connectionKeepAliveStrategy; private final HttpRequestRetryHandler defaultHttpRequestRetryHandler = (exception, executionCount, context) -> false; private SSLConnectionSocketFactory sslConnectionSocketFactory = SSLConnectionSocketFactory.getSocketFactory(); private final PlainConnectionSocketFactory plainConnectionSocketFactory = PlainConnectionSocketFactory.getSocketFactory(); private String httpProxyHost; private int httpProxyPort; private String httpProxyUsername; private String httpProxyPassword; /** * 闲置连接监控线程 */ private IdleConnectionMonitorThread idleConnectionMonitorThread; /** * 持有client对象,仅初始化一次,避免多service实例的时候造成重复初始化的问题 */ private CloseableHttpClient closeableHttpClient; private DefaultApacheHttpClientBuilder() { } public static DefaultApacheHttpClientBuilder get() { return DefaultApacheHttpClientBuilder.SingletonHolder.INSTANCE; } @Override public ApacheHttpClientBuilder httpProxyHost(String httpProxyHost) { this.httpProxyHost = httpProxyHost; return this; } @Override public ApacheHttpClientBuilder httpProxyPort(int httpProxyPort) { this.httpProxyPort = httpProxyPort; return this; } @Override public ApacheHttpClientBuilder httpProxyUsername(String httpProxyUsername) { this.httpProxyUsername = httpProxyUsername; return this; } @Override public ApacheHttpClientBuilder httpProxyPassword(String httpProxyPassword) { this.httpProxyPassword = httpProxyPassword; return this; } @Override public ApacheHttpClientBuilder httpRequestRetryHandler(HttpRequestRetryHandler httpRequestRetryHandler) { this.httpRequestRetryHandler = httpRequestRetryHandler; return this; } @Override public ApacheHttpClientBuilder keepAliveStrategy(ConnectionKeepAliveStrategy keepAliveStrategy) { this.connectionKeepAliveStrategy = keepAliveStrategy; return this; } @Override public ApacheHttpClientBuilder sslConnectionSocketFactory(SSLConnectionSocketFactory sslConnectionSocketFactory) { this.sslConnectionSocketFactory = sslConnectionSocketFactory; return this; } @Override public ApacheHttpClientBuilder supportedProtocols(String[] supportedProtocols) { this.supportedProtocols = supportedProtocols; return this; } public IdleConnectionMonitorThread getIdleConnectionMonitorThread() { return this.idleConnectionMonitorThread; } private synchronized void prepare() { if (prepared.get()) { return; } Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create() .register("http", this.plainConnectionSocketFactory) .register("https", this.sslConnectionSocketFactory) .build(); PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(registry); connectionManager.setMaxTotal(this.maxTotalConn); connectionManager.setDefaultMaxPerRoute(this.maxConnPerHost); connectionManager.setDefaultSocketConfig( SocketConfig.copy(SocketConfig.DEFAULT) .setSoTimeout(this.soTimeout) .build() ); this.idleConnectionMonitorThread = new IdleConnectionMonitorThread( connectionManager, this.idleConnTimeout, this.checkWaitTime); this.idleConnectionMonitorThread.setDaemon(true); this.idleConnectionMonitorThread.start(); HttpClientBuilder httpClientBuilder = HttpClients.custom() .setConnectionManager(connectionManager) .setConnectionManagerShared(true) .setSSLSocketFactory(this.buildSSLConnectionSocketFactory()) .setDefaultRequestConfig(RequestConfig.custom() .setSocketTimeout(this.soTimeout) .setConnectTimeout(this.connectionTimeout) .setConnectionRequestTimeout(this.connectionRequestTimeout) .build() ); // 设置重试策略,没有则使用默认 httpRequestRetryHandler = httpRequestRetryHandler == null ? defaultHttpRequestRetryHandler : httpRequestRetryHandler; httpClientBuilder.setRetryHandler(httpRequestRetryHandler); // 设置KeepAliveStrategy,没有使用默认 if (connectionKeepAliveStrategy != null) { httpClientBuilder.setKeepAliveStrategy(connectionKeepAliveStrategy); } if (StringUtils.isNotBlank(this.httpProxyHost) && StringUtils.isNotBlank(this.httpProxyUsername)) { // 使用代理服务器 需要用户认证的代理服务器 CredentialsProvider provider = new BasicCredentialsProvider(); provider.setCredentials(new AuthScope(this.httpProxyHost, this.httpProxyPort), new UsernamePasswordCredentials(this.httpProxyUsername, this.httpProxyPassword)); httpClientBuilder.setDefaultCredentialsProvider(provider); httpClientBuilder.setProxy(new HttpHost(this.httpProxyHost, this.httpProxyPort)); } if (StringUtils.isNotBlank(this.userAgent)) { httpClientBuilder.setUserAgent(this.userAgent); } //添加自定义的请求拦截器 requestInterceptors.forEach(httpClientBuilder::addInterceptorFirst); //添加自定义的响应拦截器 responseInterceptors.forEach(httpClientBuilder::addInterceptorLast); this.closeableHttpClient = httpClientBuilder.build(); prepared.set(true); } private SSLConnectionSocketFactory buildSSLConnectionSocketFactory() { try { SSLContext sslcontext = SSLContexts.custom() //忽略掉对服务器端证书的校验 .loadTrustMaterial((TrustStrategy) (chain, authType) -> true).build(); return new SSLConnectionSocketFactory( sslcontext, this.supportedProtocols, null, SSLConnectionSocketFactory.getDefaultHostnameVerifier()); } catch (NoSuchAlgorithmException | KeyManagementException | KeyStoreException e) { log.error("构建SSL连接工厂时发生异常!", e); } return null; } @Override public CloseableHttpClient build() { if (!prepared.get()) { prepare(); } return this.closeableHttpClient; } /** * DefaultApacheHttpClientBuilder 改为单例模式,并持有唯一的CloseableHttpClient(仅首次调用创建) */ private static class SingletonHolder { private static final DefaultApacheHttpClientBuilder INSTANCE = new DefaultApacheHttpClientBuilder(); } public static class IdleConnectionMonitorThread extends Thread { private final HttpClientConnectionManager connMgr; private final int idleConnTimeout; private final int checkWaitTime; private volatile boolean shutdown; public IdleConnectionMonitorThread(HttpClientConnectionManager connMgr, int idleConnTimeout, int checkWaitTime) { super("IdleConnectionMonitorThread"); this.connMgr = connMgr; this.idleConnTimeout = idleConnTimeout; this.checkWaitTime = checkWaitTime; } @Override public void run() { try { while (!this.shutdown) { synchronized (this) { wait(this.checkWaitTime); this.connMgr.closeExpiredConnections(); this.connMgr.closeIdleConnections(this.idleConnTimeout, TimeUnit.MILLISECONDS); } } } catch (InterruptedException ignore) { } } public void trigger() { synchronized (this) { notifyAll(); } } public void shutdown() { this.shutdown = true; synchronized (this) { notifyAll(); } } } }
java
Apache-2.0
84b5c4d2d0774f800237634e5d0336f53c004fe3
2026-01-04T14:46:39.499027Z
false
binarywang/WxJava
https://github.com/binarywang/WxJava/blob/84b5c4d2d0774f800237634e5d0336f53c004fe3/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/apache/InputStreamResponseHandler.java
weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/apache/InputStreamResponseHandler.java
package me.chanjar.weixin.common.util.http.apache; import org.apache.http.HttpEntity; import org.apache.http.client.ResponseHandler; import org.apache.http.impl.client.AbstractResponseHandler; import java.io.IOException; import java.io.InputStream; /** * 输入流响应处理器. * * @author altusea */ public class InputStreamResponseHandler extends AbstractResponseHandler<InputStream> { public static final ResponseHandler<InputStream> INSTANCE = new InputStreamResponseHandler(); @Override public InputStream handleEntity(HttpEntity entity) throws IOException { return entity.getContent(); } }
java
Apache-2.0
84b5c4d2d0774f800237634e5d0336f53c004fe3
2026-01-04T14:46:39.499027Z
false
binarywang/WxJava
https://github.com/binarywang/WxJava/blob/84b5c4d2d0774f800237634e5d0336f53c004fe3/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/apache/Utf8ResponseHandler.java
weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/apache/Utf8ResponseHandler.java
package me.chanjar.weixin.common.util.http.apache; import org.apache.http.HttpEntity; import org.apache.http.client.ResponseHandler; import org.apache.http.impl.client.AbstractResponseHandler; import org.apache.http.util.EntityUtils; import java.io.IOException; import java.nio.charset.StandardCharsets; /** * Utf8ResponseHandler * * @author altusea */ public class Utf8ResponseHandler extends AbstractResponseHandler<String> { public static final ResponseHandler<String> INSTANCE = new Utf8ResponseHandler(); @Override public String handleEntity(HttpEntity entity) throws IOException { return EntityUtils.toString(entity, StandardCharsets.UTF_8); } }
java
Apache-2.0
84b5c4d2d0774f800237634e5d0336f53c004fe3
2026-01-04T14:46:39.499027Z
false
binarywang/WxJava
https://github.com/binarywang/WxJava/blob/84b5c4d2d0774f800237634e5d0336f53c004fe3/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/apache/ApacheMinishopMediaUploadRequestExecutor.java
weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/apache/ApacheMinishopMediaUploadRequestExecutor.java
package me.chanjar.weixin.common.util.http.apache; import lombok.extern.slf4j.Slf4j; import me.chanjar.weixin.common.bean.result.WxMinishopImageUploadResult; import me.chanjar.weixin.common.enums.WxType; import me.chanjar.weixin.common.error.WxError; import me.chanjar.weixin.common.error.WxErrorException; import me.chanjar.weixin.common.util.http.MinishopUploadRequestExecutor; import me.chanjar.weixin.common.util.http.RequestHttp; import org.apache.http.HttpEntity; import org.apache.http.HttpHost; import org.apache.http.client.config.RequestConfig; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.mime.HttpMultipartMode; import org.apache.http.entity.mime.MultipartEntityBuilder; import org.apache.http.impl.client.CloseableHttpClient; import java.io.File; import java.io.IOException; /** * Created by ecoolper on 2017/5/5. */ @Slf4j public class ApacheMinishopMediaUploadRequestExecutor extends MinishopUploadRequestExecutor<CloseableHttpClient, HttpHost> { public ApacheMinishopMediaUploadRequestExecutor(RequestHttp<CloseableHttpClient, HttpHost> requestHttp) { super(requestHttp); } @Override public WxMinishopImageUploadResult execute(String uri, File file, WxType wxType) throws WxErrorException, IOException { HttpPost httpPost = new HttpPost(uri); if (requestHttp.getRequestHttpProxy() != null) { RequestConfig config = RequestConfig.custom().setProxy(requestHttp.getRequestHttpProxy()).build(); httpPost.setConfig(config); } if (file != null) { HttpEntity entity = MultipartEntityBuilder .create() .addBinaryBody("media", file) .setMode(HttpMultipartMode.RFC6532) .build(); httpPost.setEntity(entity); } String responseContent = requestHttp.getRequestHttpClient().execute(httpPost, Utf8ResponseHandler.INSTANCE); WxError error = WxError.fromJson(responseContent, wxType); if (error.getErrorCode() != 0) { throw new WxErrorException(error); } log.info("responseContent: {}", responseContent); return WxMinishopImageUploadResult.fromJson(responseContent); } }
java
Apache-2.0
84b5c4d2d0774f800237634e5d0336f53c004fe3
2026-01-04T14:46:39.499027Z
false
binarywang/WxJava
https://github.com/binarywang/WxJava/blob/84b5c4d2d0774f800237634e5d0336f53c004fe3/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/apache/ApacheHttpDnsClientBuilder.java
weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/apache/ApacheHttpDnsClientBuilder.java
package me.chanjar.weixin.common.util.http.apache; import org.apache.commons.lang3.StringUtils; import org.apache.http.HttpHost; import org.apache.http.auth.AuthScope; import org.apache.http.auth.UsernamePasswordCredentials; import org.apache.http.client.CredentialsProvider; import org.apache.http.client.HttpRequestRetryHandler; import org.apache.http.client.config.RequestConfig; import org.apache.http.config.Registry; import org.apache.http.config.RegistryBuilder; import org.apache.http.config.SocketConfig; import org.apache.http.conn.ConnectionKeepAliveStrategy; import org.apache.http.conn.DnsResolver; import org.apache.http.conn.HttpClientConnectionManager; import org.apache.http.conn.socket.ConnectionSocketFactory; import org.apache.http.conn.socket.PlainConnectionSocketFactory; import org.apache.http.conn.ssl.SSLConnectionSocketFactory; import org.apache.http.impl.client.BasicCredentialsProvider; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.impl.client.HttpClients; import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; import org.apache.http.protocol.HttpContext; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.annotation.concurrent.NotThreadSafe; import java.io.IOException; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; /** * httpclient 连接管理器 自带DNS解析. * <p>大部分代码拷贝自:DefaultApacheHttpClientBuilder</p> * * @author Andy.Huo */ @NotThreadSafe public class ApacheHttpDnsClientBuilder implements ApacheHttpClientBuilder { protected final Logger log = LoggerFactory.getLogger(ApacheHttpDnsClientBuilder.class); private final AtomicBoolean prepared = new AtomicBoolean(false); private int connectionRequestTimeout = 3000; private int connectionTimeout = 5000; private int soTimeout = 5000; private int idleConnTimeout = 60000; private int checkWaitTime = 60000; private int maxConnPerHost = 10; private int maxTotalConn = 50; private String userAgent; private DnsResolver dnsResolver; private HttpRequestRetryHandler httpRequestRetryHandler = (IOException exception, int executionCount, HttpContext context) -> false; private SSLConnectionSocketFactory sslConnectionSocketFactory = SSLConnectionSocketFactory.getSocketFactory(); private PlainConnectionSocketFactory plainConnectionSocketFactory = PlainConnectionSocketFactory.getSocketFactory(); private String httpProxyHost; private ConnectionKeepAliveStrategy keepAliveStrategy; private int httpProxyPort; private String httpProxyUsername; private String httpProxyPassword; /** * 闲置连接监控线程. */ private IdleConnectionMonitorThread idleConnectionMonitorThread; private HttpClientBuilder httpClientBuilder; private ApacheHttpDnsClientBuilder() { } public static ApacheHttpDnsClientBuilder get() { return new ApacheHttpDnsClientBuilder(); } @Override public ApacheHttpClientBuilder httpProxyHost(String httpProxyHost) { this.httpProxyHost = httpProxyHost; return this; } @Override public ApacheHttpClientBuilder httpProxyPort(int httpProxyPort) { this.httpProxyPort = httpProxyPort; return this; } @Override public ApacheHttpClientBuilder httpProxyUsername(String httpProxyUsername) { this.httpProxyUsername = httpProxyUsername; return this; } @Override public ApacheHttpClientBuilder httpProxyPassword(String httpProxyPassword) { this.httpProxyPassword = httpProxyPassword; return this; } @Override public ApacheHttpClientBuilder httpRequestRetryHandler(HttpRequestRetryHandler httpRequestRetryHandler) { this.httpRequestRetryHandler = httpRequestRetryHandler; return this; } @Override public ApacheHttpClientBuilder keepAliveStrategy(ConnectionKeepAliveStrategy keepAliveStrategy) { this.keepAliveStrategy = keepAliveStrategy; return this; } @Override public ApacheHttpClientBuilder sslConnectionSocketFactory(SSLConnectionSocketFactory sslConnectionSocketFactory) { this.sslConnectionSocketFactory = sslConnectionSocketFactory; return this; } @Override public ApacheHttpClientBuilder supportedProtocols(String[] supportedProtocols) { // This implementation doesn't use the supportedProtocols parameter as it relies on the provided SSLConnectionSocketFactory // Users should configure the SSLConnectionSocketFactory with desired protocols before setting it return this; } /** * 获取链接的超时时间设置,默认3000ms * <p> * 设置为零时不超时,一直等待. 设置为负数是使用系统默认设置(非上述的3000ms的默认值,而是httpclient的默认设置). * </p> * * @param connectionRequestTimeout 获取链接的超时时间设置(单位毫秒),默认3000ms */ public void setConnectionRequestTimeout(int connectionRequestTimeout) { this.connectionRequestTimeout = connectionRequestTimeout; } /** * 建立链接的超时时间,默认为5000ms.由于是在链接池获取链接,此设置应该并不起什么作用 * <p> * 设置为零时不超时,一直等待. 设置为负数是使用系统默认设置(非上述的5000ms的默认值,而是httpclient的默认设置). * </p> * * @param connectionTimeout 建立链接的超时时间设置(单位毫秒),默认5000ms */ public void setConnectionTimeout(int connectionTimeout) { this.connectionTimeout = connectionTimeout; } /** * 默认NIO的socket超时设置,默认5000ms. * * @param soTimeout 默认NIO的socket超时设置,默认5000ms. * @see java.net.SocketOptions#SO_TIMEOUT */ public void setSoTimeout(int soTimeout) { this.soTimeout = soTimeout; } /** * 空闲链接的超时时间,默认60000ms. * <p> * 超时的链接将在下一次空闲链接检查是被销毁 * </p> * * @param idleConnTimeout 空闲链接的超时时间,默认60000ms. */ public void setIdleConnTimeout(int idleConnTimeout) { this.idleConnTimeout = idleConnTimeout; } /** * 检查空间链接的间隔周期,默认60000ms. * * @param checkWaitTime 检查空间链接的间隔周期,默认60000ms. */ public void setCheckWaitTime(int checkWaitTime) { this.checkWaitTime = checkWaitTime; } /** * 每路的最大链接数,默认10. * * @param maxConnPerHost 每路的最大链接数,默认10 */ public void setMaxConnPerHost(int maxConnPerHost) { this.maxConnPerHost = maxConnPerHost; } /** * 最大总连接数,默认50. * * @param maxTotalConn 最大总连接数,默认50 */ public void setMaxTotalConn(int maxTotalConn) { this.maxTotalConn = maxTotalConn; } /** * 自定义httpclient的User Agent. * * @param userAgent User Agent */ public void setUserAgent(String userAgent) { this.userAgent = userAgent; } public IdleConnectionMonitorThread getIdleConnectionMonitorThread() { return this.idleConnectionMonitorThread; } private synchronized void prepare() { if (prepared.get()) { return; } Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create() .register("http", this.plainConnectionSocketFactory) .register("https", this.sslConnectionSocketFactory) .build(); @SuppressWarnings("resource") PoolingHttpClientConnectionManager connectionManager; if (dnsResolver != null) { if (log.isDebugEnabled()) { log.debug("specified dns resolver."); } connectionManager = new PoolingHttpClientConnectionManager(registry, dnsResolver); } else { if (log.isDebugEnabled()) { log.debug("Not specified dns resolver."); } connectionManager = new PoolingHttpClientConnectionManager(registry); } connectionManager.setMaxTotal(this.maxTotalConn); connectionManager.setDefaultMaxPerRoute(this.maxConnPerHost); connectionManager .setDefaultSocketConfig(SocketConfig.copy(SocketConfig.DEFAULT).setSoTimeout(this.soTimeout).build()); this.idleConnectionMonitorThread = new IdleConnectionMonitorThread( connectionManager, this.idleConnTimeout, this.checkWaitTime); this.idleConnectionMonitorThread.setDaemon(true); this.idleConnectionMonitorThread.start(); this.httpClientBuilder = HttpClients.custom().setConnectionManager(connectionManager) .setConnectionManagerShared(true) .setDefaultRequestConfig(RequestConfig.custom().setSocketTimeout(this.soTimeout) .setConnectTimeout(this.connectionTimeout) .setConnectionRequestTimeout(this.connectionRequestTimeout).build()) .setRetryHandler(this.httpRequestRetryHandler); if (StringUtils.isNotBlank(this.httpProxyHost) && StringUtils.isNotBlank(this.httpProxyUsername)) { // 使用代理服务器 需要用户认证的代理服务器 CredentialsProvider provider = new BasicCredentialsProvider(); provider.setCredentials(new AuthScope(this.httpProxyHost, this.httpProxyPort), new UsernamePasswordCredentials(this.httpProxyUsername, this.httpProxyPassword)); this.httpClientBuilder.setDefaultCredentialsProvider(provider); this.httpClientBuilder.setProxy(new HttpHost(this.httpProxyHost, this.httpProxyPort)); } if (StringUtils.isNotBlank(this.userAgent)) { this.httpClientBuilder.setUserAgent(this.userAgent); } prepared.set(true); } @Override public CloseableHttpClient build() { if (!prepared.get()) { prepare(); } return this.httpClientBuilder.build(); } public DnsResolver getDnsResolver() { return dnsResolver; } public void setDnsResolver(DnsResolver dnsResolver) { this.dnsResolver = dnsResolver; } public static class IdleConnectionMonitorThread extends Thread { private final HttpClientConnectionManager connMgr; private final int idleConnTimeout; private final int checkWaitTime; private volatile boolean shutdown; /** * 构造方法. */ public IdleConnectionMonitorThread(HttpClientConnectionManager connMgr, int idleConnTimeout, int checkWaitTime) { super("IdleConnectionMonitorThread"); this.connMgr = connMgr; this.idleConnTimeout = idleConnTimeout; this.checkWaitTime = checkWaitTime; } @Override public void run() { try { while (!this.shutdown) { synchronized (this) { wait(this.checkWaitTime); this.connMgr.closeExpiredConnections(); this.connMgr.closeIdleConnections(this.idleConnTimeout, TimeUnit.MILLISECONDS); } } } catch (InterruptedException ignore) { Thread.currentThread().interrupt(); } } /** * 触发. */ public void trigger() { synchronized (this) { notifyAll(); } } /** * 关闭. */ public void shutdown() { this.shutdown = true; synchronized (this) { notifyAll(); } } } }
java
Apache-2.0
84b5c4d2d0774f800237634e5d0336f53c004fe3
2026-01-04T14:46:39.499027Z
false
binarywang/WxJava
https://github.com/binarywang/WxJava/blob/84b5c4d2d0774f800237634e5d0336f53c004fe3/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/apache/ApacheMediaInputStreamUploadRequestExecutor.java
weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/apache/ApacheMediaInputStreamUploadRequestExecutor.java
package me.chanjar.weixin.common.util.http.apache; import me.chanjar.weixin.common.bean.result.WxMediaUploadResult; import me.chanjar.weixin.common.enums.WxType; import me.chanjar.weixin.common.error.WxError; import me.chanjar.weixin.common.error.WxErrorException; import me.chanjar.weixin.common.util.http.InputStreamData; import me.chanjar.weixin.common.util.http.MediaInputStreamUploadRequestExecutor; import me.chanjar.weixin.common.util.http.RequestHttp; import org.apache.http.HttpEntity; import org.apache.http.HttpHost; import org.apache.http.client.config.RequestConfig; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.ContentType; import org.apache.http.entity.mime.HttpMultipartMode; import org.apache.http.entity.mime.MultipartEntityBuilder; import org.apache.http.impl.client.CloseableHttpClient; import java.io.IOException; /** * 文件输入流上传. * * @author meiqin.zhou91@gmail.com * created on 2022/02/15 */ public class ApacheMediaInputStreamUploadRequestExecutor extends MediaInputStreamUploadRequestExecutor<CloseableHttpClient, HttpHost> { public ApacheMediaInputStreamUploadRequestExecutor(RequestHttp<CloseableHttpClient, HttpHost> requestHttp) { super(requestHttp); } @Override public WxMediaUploadResult execute(String uri, InputStreamData data, WxType wxType) throws WxErrorException, IOException { HttpPost httpPost = new HttpPost(uri); if (requestHttp.getRequestHttpProxy() != null) { RequestConfig config = RequestConfig.custom().setProxy(requestHttp.getRequestHttpProxy()).build(); httpPost.setConfig(config); } if (data != null) { HttpEntity entity = MultipartEntityBuilder .create() .addBinaryBody("media", data.getInputStream(), ContentType.DEFAULT_BINARY, data.getFilename()) .setMode(HttpMultipartMode.RFC6532) .build(); httpPost.setEntity(entity); } String responseContent = requestHttp.getRequestHttpClient().execute(httpPost, Utf8ResponseHandler.INSTANCE); WxError error = WxError.fromJson(responseContent, wxType); if (error.getErrorCode() != 0) { throw new WxErrorException(error); } return WxMediaUploadResult.fromJson(responseContent); } }
java
Apache-2.0
84b5c4d2d0774f800237634e5d0336f53c004fe3
2026-01-04T14:46:39.499027Z
false
binarywang/WxJava
https://github.com/binarywang/WxJava/blob/84b5c4d2d0774f800237634e5d0336f53c004fe3/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/apache/ApacheMediaDownloadRequestExecutor.java
weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/apache/ApacheMediaDownloadRequestExecutor.java
package me.chanjar.weixin.common.util.http.apache; import me.chanjar.weixin.common.enums.WxType; import me.chanjar.weixin.common.error.WxError; import me.chanjar.weixin.common.error.WxErrorException; import me.chanjar.weixin.common.util.fs.FileUtils; import me.chanjar.weixin.common.util.http.BaseMediaDownloadRequestExecutor; import me.chanjar.weixin.common.util.http.HttpResponseProxy; import me.chanjar.weixin.common.util.http.RequestHttp; import org.apache.commons.io.FilenameUtils; import org.apache.commons.lang3.StringUtils; import org.apache.http.Header; import org.apache.http.HttpHost; import org.apache.http.client.config.RequestConfig; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.entity.ContentType; import org.apache.http.impl.client.CloseableHttpClient; import java.io.File; import java.io.IOException; import java.io.InputStream; /** * . * * @author ecoolper * created on 2017/5/5 */ public class ApacheMediaDownloadRequestExecutor extends BaseMediaDownloadRequestExecutor<CloseableHttpClient, HttpHost> { public ApacheMediaDownloadRequestExecutor(RequestHttp<CloseableHttpClient, HttpHost> requestHttp, File tmpDirFile) { super(requestHttp, tmpDirFile); } @Override public File execute(String uri, String queryParam, WxType wxType) throws WxErrorException, IOException { if (queryParam != null) { if (uri.indexOf('?') == -1) { uri += '?'; } uri += uri.endsWith("?") ? queryParam : '&' + queryParam; } HttpGet httpGet = new HttpGet(uri); if (requestHttp.getRequestHttpProxy() != null) { RequestConfig config = RequestConfig.custom().setProxy(requestHttp.getRequestHttpProxy()).build(); httpGet.setConfig(config); } try (CloseableHttpResponse response = requestHttp.getRequestHttpClient().execute(httpGet); InputStream inputStream = InputStreamResponseHandler.INSTANCE.handleResponse(response)) { Header[] contentTypeHeader = response.getHeaders("Content-Type"); if (contentTypeHeader != null && contentTypeHeader.length > 0) { if (contentTypeHeader[0].getValue().startsWith(ContentType.APPLICATION_JSON.getMimeType())) { // application/json; encoding=utf-8 下载媒体文件出错 String responseContent = Utf8ResponseHandler.INSTANCE.handleResponse(response); throw new WxErrorException(WxError.fromJson(responseContent, wxType)); } } String fileName = HttpResponseProxy.from(response).getFileName(); if (StringUtils.isBlank(fileName)) { fileName = String.valueOf(System.currentTimeMillis()); } String baseName = FilenameUtils.getBaseName(fileName); if (StringUtils.isBlank(fileName) || baseName.length() < 3) { baseName = String.valueOf(System.currentTimeMillis()); } return FileUtils.createTmpFile(inputStream, baseName, FilenameUtils.getExtension(fileName), super.tmpDirFile); } } }
java
Apache-2.0
84b5c4d2d0774f800237634e5d0336f53c004fe3
2026-01-04T14:46:39.499027Z
false