引用依赖包
< dependency> < groupId> bouncycastle</ groupId> < artifactId> bcprov-jdk14</ artifactId> < version> 138</ version> </ dependency> < dependency> < groupId> com.alibaba</ groupId> < artifactId> fastjson</ artifactId> < version> 1.2.80</ version> </ dependency> < dependency> < groupId> io.github.admin4j</ groupId> < artifactId> http</ artifactId> < version> 0.4.6</ version> </ dependency> < dependency> < groupId> cn.hutool</ groupId> < artifactId> hutool-all</ artifactId> < version> 5.4.0</ version> </ dependency> < dependency> < groupId> org.bouncycastle</ groupId> < artifactId> bcprov-jdk15on</ artifactId> < version> 1.70</ version> </ dependency> < dependency> < groupId> com.alibaba</ groupId> < artifactId> fastjson</ artifactId> < version> 1.2.80</ version> < scope> compile</ scope> </ dependency>
AccountInfo
public class AccountInfo { public static String grantType= "client_credential" ; public static String appId= "" ; public static String appSecret= "" ; public static String accessTokenUrl= "https://api.weixin.qq.com/cgi-bin/token" ; public static String getPhoneNumberUrl= "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=" ; }
接口
if ( code == null || code. length ( ) == 0 ) { return null ; } String wxAppid = AccountInfo . appId; String wxSecret = AccountInfo . appSecret; String grant_type = AccountInfo . grantType; String params = "appid=" + wxAppid + "&secret=" + wxSecret + "&grant_type=" + grant_type; try { String sr = HttpRequest . sendGetSSL ( AccountInfo . accessTokenUrl, params) ; JSONObject json = null ; System . out. println ( "sr" ) ; System . out. println ( sr) ; json = JSON . parseObject ( sr) ; String access_token = ( String ) json. get ( "access_token" ) ; String jsonData = "{\"code\":\"" + telCode + "\"}" ; Object data = JSON . parse ( jsonData) ; String sr1 = HttpRequest . sendPostSSl ( AccountInfo . getPhoneNumberUrl + access_token, data) ; System . out. println ( "sr1" ) ; System . out. println ( sr1) ; json = JSON . parseObject ( sr1) ; Integer errcode = ( Integer ) json. get ( "errcode" ) ; if ( errcode== 0 ) { String tel = ( String ) JSON . parseObject ( json. get ( "phone_info" ) . toString ( ) ) . get ( "phoneNumber" ) ; if ( tel == null || tel. equals ( "" ) ) { return null ; } } else { } } catch ( Exception e) { return null ; }
HttpRequest
public class HttpRequest { public static void main ( String [ ] args) { String s= HttpRequest . sendGet ( "http://v.qq.com/x/cover/kvehb7okfxqstmc.html?vid=e01957zem6o" , "" ) ; System . out. println ( s) ;
} public static String sendGet ( String url, String param) { String result = "" ; BufferedReader in = null ; try { String urlNameString = url + "?" + param; URL realUrl = new URL ( urlNameString) ; URLConnection connection = realUrl. openConnection ( ) ; connection. setRequestProperty ( "accept" , "*/*" ) ; connection. setRequestProperty ( "connection" , "Keep-Alive" ) ; connection. setRequestProperty ( "user-agent" , "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)" ) ; connection. connect ( ) ; Map < String , List < String > > map = connection. getHeaderFields ( ) ; for ( String key : map. keySet ( ) ) { System . out. println ( key + "--->" + map. get ( key) ) ; } in = new BufferedReader ( new InputStreamReader ( connection. getInputStream ( ) ) ) ; String line; while ( ( line = in. readLine ( ) ) != null ) { result += line; } } catch ( Exception e) { System . out. println ( "发送GET请求出现异常!" + e) ; e. printStackTrace ( ) ; } finally { try { if ( in != null ) { in. close ( ) ; } } catch ( Exception e2) { e2. printStackTrace ( ) ; } } System . out. println ( "result" ) ; System . out. println ( result) ; return result; } public static String sendGetSSl ( String requestUrl, String param, Map < String , String > header) throws Exception { HttpsURLConnection conn = null ; InputStream input = null ; BufferedReader br = null ; StringBuffer buffer = null ; try { SSLContext sc = SSLContext . getInstance ( "SSL" ) ; sc. init ( null , new TrustManager [ ] { new TrustAnyTrustManager ( ) } , new java. security. SecureRandom( ) ) ; HttpsURLConnection . setDefaultSSLSocketFactory ( sc. getSocketFactory ( ) ) ; String urlNameString = requestUrl + "?" + param; URL url = new URL ( urlNameString) ; conn = ( HttpsURLConnection ) url. openConnection ( ) ; conn. setSSLSocketFactory ( sc. getSocketFactory ( ) ) ; conn. setHostnameVerifier ( new TrustAnyHostnameVerifier ( ) ) ; conn. setDoOutput ( false ) ; conn. setDoInput ( true ) ; conn. setUseCaches ( false ) ; conn. setConnectTimeout ( 1000 * 100 ) ; conn. setReadTimeout ( 1000 * 100 ) ; conn. setRequestMethod ( "GET" ) ; conn. setRequestProperty ( "Accept" , "*/*" ) ; conn. setRequestProperty ( "Connection" , "keep-alive" ) ; conn. setRequestProperty ( "User-Agent" , "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)" ) ; conn. setRequestProperty ( "Charset" , "UTF-8" ) ; conn. setRequestProperty ( "Content-Type" , "application/x-www-form-urlencoded" ) ; if ( header != null ) { for ( Map. Entry < String , String > entry : header. entrySet ( ) ) { String mapKey = entry. getKey ( ) ; String mapValue = entry. getValue ( ) ; conn. setRequestProperty ( mapKey, mapValue) ; } } conn. connect ( ) ; System . out. println ( "======================响应体=========================" ) ; System . out. println ( "ResponseCode:" + conn. getResponseCode ( ) + ",ResponseMessage:" + conn. getResponseMessage ( ) ) ; if ( conn. getResponseCode ( ) == 200 ) { input = conn. getInputStream ( ) ; } else { input = conn. getErrorStream ( ) ; } br = new BufferedReader ( new InputStreamReader ( input, "UTF-8" ) ) ; buffer = new StringBuffer ( ) ; String line = null ; while ( ( line = br. readLine ( ) ) != null ) { buffer. append ( line) ; } System . out. println ( "返回报文:" + buffer. toString ( ) ) ; } catch ( Exception e) { System . out. println ( "发送GET请求出现异常!" + e) ; e. printStackTrace ( ) ; } finally { try { if ( conn != null ) { conn. disconnect ( ) ; conn = null ; } if ( br != null ) { br. close ( ) ; br = null ; } } catch ( IOException ex) { throw new Exception ( ex) ; } } return buffer. toString ( ) ; } public static String sendGetSSL ( String requestUrl, String param) { String urlNameString = requestUrl + "?" + param; Response response = HttpUtil . get ( urlNameString) ; ResponseBody responseBody = response. body ( ) ; okio. BufferedSource source = responseBody. source ( ) ; try { source. request ( Long . MAX_VALUE ) ; okio. Buffer buffer = source. buffer ( ) ; Charset charset = StandardCharsets . UTF_8 ; MediaType contentType = responseBody. contentType ( ) ; if ( contentType != null ) { charset = contentType. charset ( StandardCharsets . UTF_8 ) ; } return buffer. clone ( ) . readString ( charset) ; } catch ( IOException e) { throw new RuntimeException ( e) ; } } public static String sendPostSSl ( String requestUrl, Object body) { Response response= HttpUtil . post ( requestUrl, body) ; ResponseBody responseBody = response. body ( ) ; okio. BufferedSource source = responseBody. source ( ) ; try { source. request ( Long . MAX_VALUE ) ; okio. Buffer buffer = source. buffer ( ) ; Charset charset = StandardCharsets . UTF_8 ; MediaType contentType = responseBody. contentType ( ) ; if ( contentType != null ) { charset = contentType. charset ( StandardCharsets . UTF_8 ) ; } return buffer. clone ( ) . readString ( charset) ; } catch ( IOException e) { throw new RuntimeException ( e) ; } } public static String sendPost ( String url, String param) { PrintWriter out = null ; BufferedReader in = null ; String result = "" ; try { URL realUrl = new URL ( url) ; URLConnection conn = realUrl. openConnection ( ) ; conn. setRequestProperty ( "accept" , "*/*" ) ; conn. setRequestProperty ( "connection" , "Keep-Alive" ) ; conn. setRequestProperty ( "user-agent" , "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)" ) ; conn. setDoOutput ( true ) ; conn. setDoInput ( true ) ; out = new PrintWriter ( conn. getOutputStream ( ) ) ; out. print ( param) ; out. flush ( ) ; in = new BufferedReader ( new InputStreamReader ( conn. getInputStream ( ) ) ) ; String line; while ( ( line = in. readLine ( ) ) != null ) { result += line; } } catch ( Exception e) { System . out. println ( "发送 POST 请求出现异常!" + e) ; e. printStackTrace ( ) ; } finally { try { if ( out!= null ) { out. close ( ) ; } if ( in!= null ) { in. close ( ) ; } } catch ( IOException ex) { ex. printStackTrace ( ) ; } } return result; }
}
TrustAnyHostnameVerifier
public class TrustAnyHostnameVerifier implements HostnameVerifier { public boolean verify ( String hname, SSLSession session) { return true ; }
}
TrustAnyTrustManager
public class TrustAnyTrustManager implements X509TrustManager { public void checkClientTrusted ( java. security. cert. X509Certificate[ ] var1, String var2) throws java. security. cert. CertificateException{ } public void checkServerTrusted ( java. security. cert. X509Certificate[ ] var1, String var2) throws java. security. cert. CertificateException{ } public java. security. cert. X509Certificate[ ] getAcceptedIssuers ( ) { return null ; }
}
WeChatUtil
public class WeChatUtil { public static JSONObject getSessionByCode ( String jscode) { String baseUrl = "https://api.weixin.qq.com/sns/jscode2session" ; HashMap < String , Object > requestParam = new HashMap < > ( ) ; requestParam. put ( "appid" , AccountInfo . appId) ; requestParam. put ( "secret" , AccountInfo . appSecret) ; requestParam. put ( "js_code" , jscode) ; requestParam. put ( "grant_type" , "authorization_code" ) ; String result = HttpUtil . get ( baseUrl, requestParam) ; return JSONUtil . parseObj ( result) ; } public static JSONObject getUserInfo ( String encryptData, String sessionKey, String iv) { byte [ ] dataByte = Base64 . decode ( encryptData) ; byte [ ] keyByte = Base64 . decode ( sessionKey) ; byte [ ] ivByte = Base64 . decode ( iv) ; try { int base = 16 ; if ( keyByte. length % base != 0 ) { int groups = keyByte. length / base + ( keyByte. length % base != 0 ? 1 : 0 ) ; byte [ ] temp = new byte [ groups * base] ; Arrays . fill ( temp, ( byte ) 0 ) ; System . arraycopy ( keyByte, 0 , temp, 0 , keyByte. length) ; keyByte = temp; } Security . addProvider ( new BouncyCastleProvider ( ) ) ; KeyGenerator . getInstance ( "AES" ) . init ( 128 ) ; AlgorithmParameters iv1 = AlgorithmParameters . getInstance ( "AES" ) ; iv1. init ( new IvParameterSpec ( ivByte) ) ; SecretKeySpec secretKeySpec = new SecretKeySpec ( keyByte, "AES" ) ; Cipher cipher = Cipher . getInstance ( "AES/CBC/PKCS7Padding" ) ; cipher. init ( Cipher . DECRYPT_MODE , secretKeySpec, iv1) ; byte [ ] decryptByte = cipher. doFinal ( dataByte) ; if ( null != decryptByte && decryptByte. length > 0 ) { String result = new String ( decryptByte, "UTF-8" ) ; return JSONUtil . parseObj ( result) ; } } catch ( Exception e) { e. printStackTrace ( ) ; } return null ; }
}