加密
package com. itsoft. customer. commons. wx ;
import java. security. MessageDigest ;
public class Sha1 {
private static final char [ ] HEX_DIGITS = { '0' , '1' , '2' , '3' , '4' , '5' ,
'6' , '7' , '8' , '9' , 'a' , 'b' , 'c' , 'd' , 'e' , 'f' } ;
private static String getFormattedText ( byte [ ] bytes) {
int len = bytes. length;
StringBuilder buf = new StringBuilder ( len * 2 ) ;
for ( int j = 0 ; j < len; j++ ) {
buf. append ( HEX_DIGITS[ ( bytes[ j] >> 4 ) & 0x0f ] ) ;
buf. append ( HEX_DIGITS[ bytes[ j] & 0x0f ] ) ;
}
return buf. toString ( ) ;
}
public static String encode ( String str) {
if ( str == null ) {
return null ;
}
try {
MessageDigest messageDigest = MessageDigest . getInstance ( "SHA1" ) ;
messageDigest. update ( str. getBytes ( ) ) ;
return getFormattedText ( messageDigest. digest ( ) ) ;
} catch ( Exception e) {
throw new RuntimeException ( e) ;
}
}
}
随机字符串
package com. itsoft. customer. commons. wx ;
import java. util. Random ;
public class RandomStr {
private static char ch[ ] = { '0' , '1' , '2' , '3' , '4' , '5' , '6' , '7' , '8' , '9' , 'A' , 'B' , 'C' , 'D' , 'E' , 'F' , 'G' ,
'H' , 'I' , 'J' , 'K' , 'L' , 'M' , 'N' , 'O' , 'P' , 'Q' , 'R' , 'S' , 'T' , 'U' , 'V' , 'W' , 'X' , 'Y' , 'Z' , 'a' , 'b' ,
'c' , 'd' , 'e' , 'f' , 'g' , 'h' , 'i' , 'j' , 'k' , 'l' , 'm' , 'n' , 'o' , 'p' , 'q' , 'r' , 's' , 't' , 'u' , 'v' , 'w' ,
'x' , 'y' , 'z' , '0' , '1' } ;
private static Random random = new Random ( ) ;
public static String createRandomString ( int length) {
if ( length > 0 ) {
int index = 0 ;
char [ ] temp = new char [ length] ;
int num = random. nextInt ( ) ;
for ( int i = 0 ; i < length % 5 ; i++ ) {
temp[ index++ ] = ch[ num & 63 ] ;
num >>= 6 ;
}
for ( int i = 0 ; i < length / 5 ; i++ ) {
num = random. nextInt ( ) ;
for ( int j = 0 ; j < 5 ; j++ ) {
temp[ index++ ] = ch[ num & 63 ] ;
num >>= 6 ;
}
}
return new String ( temp, 0 , length) ;
}
else if ( length == 0 ) {
return "" ;
}
else {
throw new IllegalArgumentException ( ) ;
}
}
public static void main ( String [ ] args) {
System . out. println ( createRandomString ( 16 ) ) ;
}
}
发送请求
package com. itsoft. customer. controller ;
import cn. hutool. json. JSONUtil ;
import com. itsoft. customer. commons. interceptor. ResponseResult ;
import com. itsoft. customer. commons. wx. RandomStr ;
import com. itsoft. customer. commons. wx. Sha1 ;
import com. itsoft. framework. core. data. DataMap ;
import com. itsoft. framework. core. data. Result ;
import io. swagger. annotations. Api ;
import io. swagger. annotations. ApiOperation ;
import org. apache. commons. lang. StringUtils ;
import org. apache. http. HttpEntity ;
import org. apache. http. HttpResponse ;
import org. apache. http. StatusLine ;
import org. apache. http. client. ClientProtocolException ;
import org. apache. http. client. HttpClient ;
import org. apache. http. client. HttpResponseException ;
import org. apache. http. client. ResponseHandler ;
import org. apache. http. client. methods. HttpGet ;
import org. apache. http. conn. ssl. SSLConnectionSocketFactory ;
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. util. EntityUtils ;
import org. json. JSONException ;
import org. json. JSONObject ;
import org. springframework. stereotype. Controller ;
import org. springframework. web. bind. annotation. RequestMapping ;
import org. springframework. web. bind. annotation. RequestMethod ;
import org. springframework. web. bind. annotation. ResponseBody ;
import org. springframework. web. bind. annotation. RestController ;
import javax. net. ssl. SSLContext ;
import javax. net. ssl. TrustManager ;
import javax. net. ssl. X509TrustManager ;
import java. io. IOException ;
import java. net. URI;
import java. security. cert. CertificateException ;
import java. security. cert. X509Certificate ;
import java. util. HashMap ;
import java. util. Map ;
@RestController
@RequestMapping ( value = "/frontendGetWx" , produces = "application/json;charset=UTF-8" )
@ResponseResult
@Api ( value = "(getWx)getWx 微信权限" , tags = "(getWx)getWx 微信权限" )
public class ShareController extends CommonController {
private String appid= "wx" ;
private String secret= "db" ;
@ApiOperation ( notes = "获取微信分享配置的请求 方法只写了主要方法,需要根据自己的要求 完善代码" , value = "获取微信分享配置的请求 方法只写了主要方法,需要根据自己的要求 完善代码" )
@RequestMapping ( value = "/getWxConfig" , method = RequestMethod . POST)
public Result share ( String url) {
long timestamp = System . currentTimeMillis ( ) / 1000 ;
String noncestr = RandomStr . createRandomString ( 16 ) ;
String ticket = getJsapiTicket ( ) ;
String str = "jsapi_ticket=" + ticket + "&noncestr=" + noncestr + "×tamp=" + timestamp + "&url=" + url;
logger. info ( "===============签名str:{}============" , str) ;
String signature = Sha1 . encode ( str) ;
Map map= new HashMap ( ) ;
map. put ( "appId" , appid) ;
map. put ( "timestamp" , timestamp) ;
map. put ( "nonceStr" , noncestr) ;
map. put ( "signature" , signature) ;
return Result . success ( map) ;
}
public String getJsapiTicket ( ) {
String tokenUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential" ;
tokenUrl = tokenUrl + "&appid=" + appid + "&secret=" + secret;
JSONObject tokenJson= new JSONObject ( ) ;
tokenJson= getUrlResponse ( tokenUrl) ;
logger. info ( "===============tokenJson:{}============" , tokenJson. toString ( ) ) ;
String token= "" ;
try {
token= tokenJson. getString ( "access_token" ) ;
} catch ( JSONException e) {
e. printStackTrace ( ) ;
logger. info ( "===============报错了{}============" , e) ;
System . out. println ( "报错了" ) ;
return null ;
}
String jsapiTicketUrl= "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=ACCESS_TOKEN&type=jsapi" ;
JSONObject jsapiTickeJson= new JSONObject ( ) ;
System . out. println ( "getJsapiTicket:获取token:" + token) ;
if ( StringUtils . isNotBlank ( token) ) {
jsapiTicketUrl = jsapiTicketUrl. replace ( "ACCESS_TOKEN" , token) ;
jsapiTickeJson= getUrlResponse ( jsapiTicketUrl) ;
logger. info ( "===============tokenJson:{}============" , jsapiTickeJson. toString ( ) ) ;
try {
return ( String ) jsapiTickeJson. get ( "ticket" ) ;
} catch ( JSONException e) {
e. printStackTrace ( ) ;
return null ;
}
} else {
return null ;
}
}
private JSONObject getUrlResponse ( String url) {
CharsetHandler handler = new CharsetHandler ( "UTF-8" ) ;
try {
HttpGet httpget = new HttpGet ( new URI ( url) ) ;
HttpClientBuilder httpClientBuilder = HttpClientBuilder . create ( ) ;
CloseableHttpClient client = httpClientBuilder. build ( ) ;
client = ( CloseableHttpClient ) wrapClient ( client) ;
return new JSONObject ( client. execute ( httpget, handler) ) ;
} catch ( Exception e) {
e. printStackTrace ( ) ;
return null ;
}
}
private static HttpClient wrapClient ( HttpClient base) {
try {
SSLContext ctx = SSLContext . getInstance ( "TLSv1" ) ;
X509TrustManager tm = new X509TrustManager ( ) {
public void checkClientTrusted ( X509Certificate [ ] xcs,
String string) throws CertificateException {
}
public void checkServerTrusted ( X509Certificate [ ] xcs,
String string) throws CertificateException {
}
public X509Certificate [ ] getAcceptedIssuers ( ) {
return null ;
}
} ;
ctx. init ( null , new TrustManager [ ] { tm } , null ) ;
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory ( ctx, new String [ ] { "TLSv1" } , null ,
SSLConnectionSocketFactory . BROWSER_COMPATIBLE_HOSTNAME_VERIFIER) ;
CloseableHttpClient httpclient = HttpClients . custom ( ) . setSSLSocketFactory ( sslsf) . build ( ) ;
return httpclient;
} catch ( Exception ex) {
return null ;
}
}
private class CharsetHandler implements ResponseHandler < String > {
private String charset;
public CharsetHandler ( String charset) {
this . charset = charset;
}
public String handleResponse ( HttpResponse response)
throws ClientProtocolException , IOException {
StatusLine statusLine = response. getStatusLine ( ) ;
if ( statusLine. getStatusCode ( ) >= 300 ) {
throw new HttpResponseException ( statusLine. getStatusCode ( ) ,
statusLine. getReasonPhrase ( ) ) ;
}
HttpEntity entity = response. getEntity ( ) ;
if ( entity != null ) {
if ( ! StringUtils . isBlank ( charset) ) {
return EntityUtils . toString ( entity, charset) ;
} else {
return EntityUtils . toString ( entity) ;
}
} else {
return null ;
}
}
}
}