静态页面
<img class="u-qrcode" src="../resume/getWxQrCode?randomKey=${randomKey}" alt="这个一个二维码">
randomKey不是必须的,这是根据业务需求添加的。
控制器代码
@RequestMapping(value = "/getWxQrCode")
@ResponseBody
public String getWxQrCode(HttpServletRequest request, HttpServletResponse response, String randomKey) {
LOG.info("###### 二维码配套的randomKey=" + randomKey);
InputStream fis = null;
OutputStream os = null;
try {
fis = WeiXinCgiUtil.getWxQrCode(randomKey);
os = response.getOutputStream();
int count = 0;
byte[] buffer = new byte[1024 * 8];
while ((count = fis.read(buffer)) != -1) {
os.write(buffer, 0, count);
os.flush();
}
} catch (Exception e) {
e.printStackTrace();
}
try {
fis.close();
os.close();
} catch (IOException e) {
e.printStackTrace();
}
return "any";
}
WeiXinCgiUtil.java
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang.builder.ToStringBuilder;
import org.apache.commons.lang.builder.ToStringStyle;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
/**
* 调用微信小程序HTTPS接口
*/
public class WeiXinCgiUtil {
private static final Logger LOG = LoggerFactory.getLogger(WeiXinCgiUtil.class);
public static String getWxToken() {
String url = Constants.WS.TOKEN_CGI;
String queryString = "appid=" + Constants.WS.APP_ID + "&secret=" + Constants.WS.APP_SECRET + "&grant_type=" + Constants.WS.GRANT_TYPE;
String charset = "UTF-8";
boolean pretty = false;
String jsonStr = HttpsUtil.doGet(url, queryString, charset, pretty);
LOG.info("###### 小程序Token JSON=" + jsonStr);
JSONObject jsonObj = JSONObject.parseObject(jsonStr);
AccessTokenVO vo = JSON.toJavaObject(jsonObj, AccessTokenVO.class);
LOG.info("###### json2Obj=" + ToStringBuilder.reflectionToString(vo, ToStringStyle.MULTI_LINE_STYLE));
return vo.getAccess_token();
}
public static InputStream getWxQrCode(String uuid) {
// testGet()生成的,有超时时间
String token = getWxToken();
LOG.info("###### 调用微信HTTPS接口生成二维码,token=" + token + ",uuid=" + uuid);
String url = Constants.WS.TRADITIONAL_QRCODE_CGI + token;
Map<String, String> params = new HashMap<String, String>();
// randomKey是随便起的名称,只要保持一致即可,后面是UUID,每个用户随机生成一个
params.put("path", "resume/myResume?randomKey=" + uuid);
params.put("appid", Constants.WS.APP_ID);
JSONObject json = new JSONObject();
json.putAll(params);
String content =json.toJSONString();
String charset = "UTF-8";
byte[] byteArr = HttpsUtil.writePost(url, content, charset);
return new ByteArrayInputStream(byteArr);
}
/**
* 将一个字符串转化为输入流
*/
public static InputStream getStringStream(String sInputString) {
if (sInputString != null && !sInputString.trim().equals("")) {
try {
ByteArrayInputStream tInputStringStream = new ByteArrayInputStream(sInputString.getBytes());
return tInputStringStream;
}
catch (Exception ex) {
ex.printStackTrace();
}
}
return null;
}
/**
* 获取二维码,进入小程序某页面,并带参数
* @param params
* @return
*/
public static InputStream getSmallProgramQrCode(Map<String, String> params,String token) {
String url = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=" + token;
JSONObject json = new JSONObject();
json.putAll(params);
String content =json.toJSONString();
String charset = "UTF-8";
byte[] byteArr = HttpsUtil.writePost(url, content, charset);
return new ByteArrayInputStream(byteArr);
}
}
HttpsUtil.java
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Map;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.URIException;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.RequestEntity;
import org.apache.commons.httpclient.methods.StringRequestEntity;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.apache.commons.httpclient.protocol.Protocol;
import org.apache.commons.httpclient.util.URIUtil;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class HttpsUtil {
private static final Logger LOG = LoggerFactory.getLogger(HttpsUtil.class);
/**
* 执行一个http/https get请求,返回请求响应的文本数据
*
* @param url 请求的URL地址
* @param queryString 请求的查询参数,可以为null
* @param charset 字符集
* @param pretty 是否美化
* @return 返回请求响应的文本数据
*/
public static String doGet(String url, String queryString, String charset, boolean pretty) {
StringBuffer response = new StringBuffer();
HttpClient client = new HttpClient();
if(url.startsWith("https")){
//https请求
Protocol myhttps = new Protocol("https", new MySSLProtocolSocketFactory(), 443);
Protocol.registerProtocol("https", myhttps);
}
HttpMethod method = new GetMethod(url);
try {
if (StringUtils.isNotBlank(queryString)) {
//对get请求参数编码,汉字编码后,就成为%式样的字符串
method.setQueryString(URIUtil.encodeQuery(queryString));
}
client.executeMethod(method);
if (method.getStatusCode() == HttpStatus.SC_OK) {
BufferedReader reader = new BufferedReader(new InputStreamReader(method.getResponseBodyAsStream(), charset));
String line;
while ((line = reader.readLine()) != null) {
if (pretty)
response.append(line).append(System.getProperty("line.separator"));
else
response.append(line);
}
reader.close();
}
} catch (URIException e) {
LOG.error("执行Get请求时,编码查询字符串“" + queryString + "”发生异常!", e);
} catch (IOException e) {
LOG.error("执行Get请求" + url + "时,发生异常!", e);
} finally {
method.releaseConnection();
}
return response.toString();
}
/**
* 执行一个http/https post请求,返回请求响应的文本数据
*
* @param url 请求的URL地址
* @param params 请求的查询参数,可以为null
* @param charset 字符集
* @param pretty 是否美化
* @return 返回请求响应的文本数据
*/
public static String doPost(String url, Map<String, String> params, String charset, boolean pretty) {
StringBuffer response = new StringBuffer();
HttpClient client = new HttpClient();
if(url.startsWith("https")){
//https请求
Protocol myhttps = new Protocol("https", new MySSLProtocolSocketFactory(), 443);
Protocol.registerProtocol("https", myhttps);
}
PostMethod method = new PostMethod(url);
//设置参数的字符集
method.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET,charset);
//设置post数据
if (params != null) {
//HttpMethodParams p = new HttpMethodParams();
for (Map.Entry<String, String> entry : params.entrySet()) {
//p.setParameter(entry.getKey(), entry.getValue());
method.setParameter(entry.getKey(), entry.getValue());
}
//method.setParams(p);
}
try {
client.executeMethod(method);
if (method.getStatusCode() == HttpStatus.SC_OK) {
BufferedReader reader = new BufferedReader(new InputStreamReader(method.getResponseBodyAsStream(), charset));
String line;
while ((line = reader.readLine()) != null) {
if (pretty)
response.append(line).append(System.getProperty("line.separator"));
else
response.append(line);
}
reader.close();
}
} catch (IOException e) {
LOG.error("执行Post请求" + url + "时,发生异常!", e);
} finally {
method.releaseConnection();
}
return response.toString();
}
/**
* 执行一个http/https post请求, 直接写数据 json,xml,txt
*
* @param url 请求的URL地址
* @param charset 字符集
* @param pretty 是否美化
* @return 返回请求响应的文本数据
*/
public static String writePost(String url, String content, String charset, boolean pretty) {
StringBuffer response = new StringBuffer();
HttpClient client = new HttpClient();
client.getParams().setConnectionManagerTimeout(6000);
if(url.startsWith("https")){
//https请求
Protocol myhttps = new Protocol("https", new MySSLProtocolSocketFactory(), 443);
Protocol.registerProtocol("https", myhttps);
}
PostMethod method = new PostMethod(url);
try {
//设置请求头部类型参数
method.setRequestHeader("Content-Type","application/xml; charset=utf-8");//application/json,text/xml,text/plain
//method.setRequestBody(content); //InputStream,NameValuePair[],String
//RequestEntity是个接口,有很多实现类,发送不同类型的数据
RequestEntity requestEntity = new StringRequestEntity(content,"application/xml",charset);//application/json,text/xml,text/plain
method.setRequestEntity(requestEntity);
client.executeMethod(method);
if (method.getStatusCode() == HttpStatus.SC_OK) {
BufferedReader reader = new BufferedReader(new InputStreamReader(method.getResponseBodyAsStream(), charset));
String line;
while ((line = reader.readLine()) != null) {
if (pretty)
response.append(line).append(System.getProperty("line.separator"));
else
response.append(line);
}
reader.close();
}
} catch (Exception e) {
LOG.error("执行Post请求" + url + "时,发生异常!", e);
} finally {
method.releaseConnection();
}
return response.toString();
}
public static byte[] writePost(String url, String content, String charset) {
byte[] byteArr = null;
StringBuffer response = new StringBuffer();
HttpClient client = new HttpClient();
client.getParams().setConnectionManagerTimeout(6000);
if(url.startsWith("https")){
//https请求
Protocol myhttps = new Protocol("https", new MySSLProtocolSocketFactory(), 443);
Protocol.registerProtocol("https", myhttps);
}
PostMethod method = new PostMethod(url);
try {
//设置请求头部类型参数
method.setRequestHeader("Content-Type","application/xml; charset=utf-8");//application/json,text/xml,text/plain
//method.setRequestBody(content); //InputStream,NameValuePair[],String
//RequestEntity是个接口,有很多实现类,发送不同类型的数据
RequestEntity requestEntity = new StringRequestEntity(content,"application/xml",charset);//application/json,text/xml,text/plain
method.setRequestEntity(requestEntity);
client.executeMethod(method);
if (method.getStatusCode() == HttpStatus.SC_OK) {
byteArr = method.getResponseBody();
// inputStream = method.getResponseBodyAsStream();
}
} catch (Exception e) {
LOG.error("执行Post请求" + url + "时,发生异常!", e);
} finally {
method.releaseConnection();
}
return byteArr;
}
public static void main(String[] args) {
try {
String y = doGet("http://video.sina.com.cn/life/tips.html", null, "GBK", true);
System.out.println(y);
// Map params = new HashMap();
// params.put("param1", "value1");
// params.put("json", "{\"aa\":\"11\"}");
// String j = doPost("http://localhost/uplat/manage/test.do?reqCode=add", params, "UTF-8", true);
// System.out.println(j);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public static final class WS {
public static final String APP_ID = "YOUR_APP_ID";
public static final String APP_SECRET = "YOUR_APP_SECRET";
public static final String GRANT_TYPE = "client_credential";
public static final String TOKEN_CGI = "https://api.weixin.qq.com/cgi-bin/token";
public static final String TRADITIONAL_QRCODE_CGI = "https://api.weixin.qq.com/cgi-bin/wxaapp/createwxaqrcode?access_token=";
public static final String JUHUA_QRCODE_CGI = "https://api.weixin.qq.com/wxa/getwxacode?access_token=";
private WS() {
}
}