微信官方文档:https://developers.weixin.qq.com/miniprogram/dev/framework/open-ability/qr-code.html
本工具采用接口A。
1.HttpUtil工具
import org.apache.http.*;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.ssl.SSLContextBuilder;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.net.ssl.SSLContext;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URI;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
/**
*/
public class HttpUtil {
private static Logger logger = LoggerFactory.getLogger(HttpUtil.class);
/**创建微信二维码工具用到(1)
* get请求
* @return
*/
public static String doGet(String url) {
try {
CloseableHttpClient client = createSSLClientDefault();
//发送get请求
HttpGet request = new HttpGet(url);
HttpResponse response = client.execute(request);
/**请求发送成功,并得到响应**/
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
/**读取服务器返回过来的json字符串数据**/
String strResult = EntityUtils.toString(response.getEntity());
return strResult;
}
}
catch (IOException e) {
e.printStackTrace();
}
return null;
}
/**
* post请求(用于key-value格式的参数)
* @param url
* @param params
* @return
*/
public static String doPost(String url, Map params){
BufferedReader in = null;
try {
CloseableHttpClient client = createSSLClientDefault();
HttpPost request = new HttpPost();
request.setURI(new URI(url));
//设置参数
List nvps = new ArrayList();
for (Iterator iter = params.keySet().iterator(); iter.hasNext();) {
String name = (String) iter.next();
String value = String.valueOf(params.get(name));
nvps.add(new BasicNameValuePair(name, value));
//System.out.println(name +"-"+value);
}
request.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));
HttpResponse response = client.execute(request);
int code = response.getStatusLine().getStatusCode();
if(code == 200){ //请求成功
in = new BufferedReader(new InputStreamReader(response.getEntity()
.getContent(),"utf-8"));
StringBuffer sb = new StringBuffer("");
String line = "";
String NL = System.getProperty("line.separator");
while ((line = in.readLine()) != null) {
sb.append(line + NL);
}
in.close();
return sb.toString();
}
else{ //
System.out.println("状态码:" + code);
return null;
}
}
catch(Exception e){
e.printStackTrace();
return null;
}
}
/**
* post请求(用于请求json格式的参数)
* @param url
* @param params
* @return
*/
public static String doPost(String url, String params) throws Exception {
CloseableHttpClient httpclient = createSSLClientDefault();
HttpPost httpPost = new HttpPost(url);// 创建httpPost
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Content-Type", "application/json");
String charSet = "UTF-8";
StringEntity entity = new StringEntity(params, charSet);
httpPost.setEntity(entity);
CloseableHttpResponse response = null;
try {
response = httpclient.execute(httpPost);
StatusLine status = response.getStatusLine();
int state = status.getStatusCode();
if (state == HttpStatus.SC_OK) {
HttpEntity responseEntity = response.getEntity();
String jsonString = EntityUtils.toString(responseEntity);
return jsonString;
}
else{
logger.error("请求返回:"+state+"("+url+")");
}
}
finally {
if (response != null) {
try {
response.close();
} catch (IOException e) {
e.printStackTrace();
}
}
try {
httpclient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
/**创建微信二维码工具用到(2)
* post请求(用于请求json格式的参数)
* @param url
* @param params
* @return byte[]
*/
public static byte[] doPostReturnStream(String url, String params) throws Exception {
CloseableHttpClient httpclient = createSSLClientDefault();
HttpPost httpPost = new HttpPost(url);// 创建httpPost
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Content-Type", "application/json");
String charSet = "UTF-8";
StringEntity entity = new StringEntity(params, charSet);
httpPost.setEntity(entity);
CloseableHttpResponse response = null;
try {
response = httpclient.execute(httpPost);
StatusLine status = response.getStatusLine();
int state = status.getStatusCode();
if (state == HttpStatus.SC_OK) {
HttpEntity responseEntity = response.getEntity();
return EntityUtils.toByteArray(responseEntity);
} else {
logger.error("请求返回:"+state+"("+url+")");
}
}
finally {
if (response != null) {
try {
response.close();
} catch (IOException e) {
e.printStackTrace();
}
}
try {
httpclient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
/**
* 略过安全检查,信任所有SSL证书
* @return CloseableHttpClient
*/
private static CloseableHttpClient createSSLClientDefault(){
try {
SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null,
//忽略条件,信任所有证书
(X509Certificate[] chain, String authType) -> {
return true;
}).build();
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext);
return HttpClients.custom().setSSLSocketFactory(sslsf).build();
} catch (Exception e) {
e.printStackTrace();
}
return HttpClients.createDefault();
}
}
2.配置文件:weChat.properties
#微信授权登录配置
weChat.appId = *
weChat.AppSecret = *
3.生成微信二维码
(1)首先获取token
(2)调用微信接口获取微信小程序二维码
(3)流上传到网易云(或阿里云),这里上传到网易云
注意!!!:微信返回的流不能直接上传或下载,做字节处理后才能正常上传下载。不然获得的EofSensorInputStream流是不能用的。
import org.titan.article.entity.QcCodeParamEntity;
import org.titan.framework.facade.json.JsonParser;
import org.titan.socialtools.common.entity.ATResultEntity;
import org.titan.socialtools.common.utils.Conf;
import org.titan.socialtools.common.utils.HttpUtil;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.util.Properties;
public class WeChatUtil {
static String appId = "";
static String appSecret = "";
public static String getAccessToken(String appId, String appSecret){
String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appId + "&secret=" + appSecret;
String result = HttpUtil.doGet(url);
ATResultEntity entity = JsonParser.getObject(result, ATResultEntity.class);
if (entity.getErrcode() != null){
System.err.println(result);
return null;
}else {
//manager().cache.save("access_token", entity.getAccess_token());
return entity.getAccess_token();
}
}
public static String getQcCode(String articleId) {
try {
Properties properties = Conf.getProperties("conf/weChat.properties");
appId = properties.getProperty("weChat.appId");
appSecret = properties.getProperty("weChat.AppSecret");
////(1)获取token
String token = getAccessToken(appId,appSecret);
//QcCodeParamEntity实体,根据微信文档创建的实体,将必传参path传入,token在url上已传入,这里只传这两个必传参
QcCodeParamEntity qcCodeParamEntity = new QcCodeParamEntity();
qcCodeParamEntity.setPath("pages/index/index?articleId=" + articleId);
//获取json格式的数据
String json = JsonParser.getJson(qcCodeParamEntity);
String url = "https://api.weixin.qq.com/wxa/getwxacode?access_token=" + token;
//(2)获取为微信返回的二维码并处理
byte[] bytes = HttpUtil.doPostReturnStream(url, json);
InputStream inputStream = new ByteArrayInputStream(bytes);
//(3)上传到网易云服务器,返回而二维码图片路径
return NosUpload.uploadQcCode(inputStream, articleId + ".jpeg");
}catch (Exception e){
e.printStackTrace();
}
return null;
}
}
QcCodeParamEntity
public class QcCodeParamEntity {
private static final long serialVersionUID = -5251129482601911011L;
private String path;
private Integer width;
private Boolean auto_color;
private Object line_color;
private Boolean is_hyaline;
public String getPath() {
return path;
}
public void setPath(String path) {
this.path = path;
}
public Integer getWidth() {
return width;
}
public void setWidth(Integer width) {
this.width = width;
}
public Boolean getAuto_color() {
return auto_color;
}
public void setAuto_color(Boolean auto_color) {
this.auto_color = auto_color;
}
public Object getLine_color() {
return line_color;
}
public void setLine_color(Object line_color) {
this.line_color = line_color;
}
public Boolean getIs_hyaline() {
return is_hyaline;
}
public void setIs_hyaline(Boolean is_hyaline) {
this.is_hyaline = is_hyaline;
}
}
网易云上传图片工具:NosUpload
import com.netease.cloud.ClientConfiguration;
import com.netease.cloud.Protocol;
import com.netease.cloud.auth.BasicCredentials;
import com.netease.cloud.auth.Credentials;
import com.netease.cloud.services.nos.NosClient;
import com.netease.cloud.services.nos.model.ObjectMetadata;
import org.titan.socialtools.common.utils.Conf;
import java.io.InputStream;
import java.util.Properties;
public class NosUpload {
public static String uploadQcCode(InputStream inputStream, String fileName){
Properties p = null;
String accessKey = "";
String secretKey = "";
String endpoint = "";
String path = "article/qcCode/" + fileName;
try {
p = Conf.getProperties("conf/nos.properties");
accessKey = p.getProperty("NOS.accessKeyId");
secretKey = p.getProperty("NOS.accessKeySecret");
endpoint = p.getProperty("NOS.endpoint");
}catch (Exception e){
e.printStackTrace();
}
Credentials credentials = new BasicCredentials(accessKey, secretKey);
ClientConfiguration configuration = new ClientConfiguration();
configuration.setProtocol(Protocol.HTTPS);
configuration.setMaxErrorRetry(5);
configuration.setSocketTimeout(30000);
NosClient nosClient = new NosClient(credentials, configuration);
nosClient.setEndpoint(endpoint);
try {
ObjectMetadata objectMetadata = new ObjectMetadata();
objectMetadata.setContentLength(inputStream.available());
objectMetadata.setContentType("image/jpeg");
//上传路径
nosClient.putObject("tgk", path, inputStream, objectMetadata);
}catch (Exception e){
e.printStackTrace();
}
//返回图片路径
return "http://"+"tgk."+ endpoint +"/" + path;
}
}
nos.properties配置:
NOS.endpoint=*
NOS.accessKeyId=*
NOS.accessKeySecret=*
#NOS.bucket=*