请求二维码并展示
步骤:
用户点击按钮生成二维码
步骤:
1、微信小程序往后台请求二维码
2、后台(java/php) 根据微信小程序信息往微信端请求tonken
3、后台得到tonken后往微信端请求二维码图片
4、后台得到图片后保存在服务器上,将路径返回给微信小程序
5、微信小程序得到路径后,根据路径下载图片
6、下载图片成功后再保存至本地
7、保存成功后将路径给予image标签里面展示
代码:
wxml
[AppleScript]
- <image class="scanimg" src="{{filePath}}" bindtap="getAgain"></image>
- <button type="primary" bindtap="primary">点击生成二维码</button>
js代码
[AppleScript]
- primary:function (e) {
- var _url = '后台地址';
- wx.request({
- url: _url,
- //请求报文体
- data: [{
- id: agentCode
- }],
- method: 'POST',
- header: {
- 'content-type': 'application/json'
- },
- success: function (res) {
- //为00时表示成功,得到二维码的地址
- if (res.data.code == '00') {
- console.log("成功")
- //下载二维码
- wx.downloadFile({
- url: res.data.body[0].URL,
- success: function (res) {
- //如果二维码中的id为固定值可以将图片保存到本地,否则不用保存
- wx.saveFile({
- tempFilePath: res.tempFilePath,
- success: function (res) {
- console.log("保存成功")
- _that.setData({
- filePath: res.savedFilePath
- })
- console.log(res.savedFilePath)
- try {
- //id为定值,则将保存的地址存入缓存,非定值则只需要setData就行
- wx.setStorageSync('filePath', res.savedFilePath)
- } catch (e) {
- console.log(e)
- }
- },
- fail: function (res) {
- console.log("保存失败")
- console.log(res)
- }
- })
- }, fail: function (res) {
- util.msg("错误", "通讯失败")
- console.log(res)
- }
- })
- } else {
- console.log("错误")
- util.msg("错误", res.data.msg)
- }
- },
- fail: function () {
- util.msg("错误", "通讯失败")
- console.log(res)
- }
- })
- }
java端代码
[Java]
- // 访问微信后台的URL
- String URL = systemConfig.getString("LoginOrRegisterUrl");
- // 请求类型
- String grant_type = systemConfig.getString("grant_type");
- // 第三方用户唯一凭证密钥
- String secret = systemConfig.getString("secret");
- // 第三方用户唯一凭证
- String appId = systemConfig.getString("appid");
- // 请求token时用到的URL
- String tokenUrl = systemConfig.getString("tokenUrl");
- // 向微信后台请求获取token
- String sendGet = HttpClientConnectionManager.sendGet(
- tokenUrl, "grant_type=" + grant_type
- + "&secret=" + secret + "&appid="
- + appId + "");
- System.out.println(sendGet);
- JSONObject json = JSONObject.fromObject(sendGet);
- access_token = json.get("access_token").toString();
- if (access_token == null) {
- //没有token 则返回错误码和错误信息
- agentDTO.setCode("0002");
- agentDTO.setDesc("获取tokenId失败");
- return agentDTO;
- }
- System.out.println(access_token);
- // 访问微信后台带的json参数
- Map<String, Object> map = new HashMap<String, Object>();
- map.put("path", "pages/register");//你二维码中跳向的地址
- map.put("width", "430");//图片大小
- JSONObject json = JSONObject.fromObject(map);
- HttpClientConnectionManager.httpPostWithJSON(URL
- + access_token, json.toString(), id + "max");
- // 返回给前端的后台服务器文件读取路径
- String downloadUrl = systemConfig
- .getString("agentImgDownloadUrl")
- + id
- + "max"
- + "/";
- // 返回给前端的后台服务器文件下载路径
- String downloadfileUrl = downloadUrl + id + "max" + ".jpg";
- agentResView.setURL(downloadfileUrl);
- agentDTO.setAgentResView(agentResView);
- agentDTO.setCode("00");
- agentDTO.setDesc("成功");
- return agentDTO;
HttpClientConnectionManager.java 文件
[Java]
- package com.hsh.utils.http;
- import java.io.BufferedReader;
- import java.io.File;
- import java.io.FileNotFoundException;
- import java.io.FileOutputStream;
- import java.io.IOException;
- import java.io.InputStream;
- import java.io.InputStreamReader;
- import java.io.ObjectOutputStream;
- import java.net.URL;
- import java.net.URLConnection;
- import java.net.URLEncoder;
- import java.util.List;
- import java.util.Locale;
- import java.util.Map;
- import java.util.ResourceBundle;
- import net.sf.json.JSONObject;
- import org.apache.http.HttpEntity;
- import org.apache.http.HttpResponse;
- import org.apache.http.client.HttpClient;
- import org.apache.http.client.methods.HttpPost;
- import org.apache.http.conn.ClientConnectionManager;
- import org.apache.http.conn.scheme.Scheme;
- import org.apache.http.conn.scheme.SchemeRegistry;
- import org.apache.http.entity.StringEntity;
- import org.apache.http.impl.client.DefaultHttpClient;
- import org.apache.http.message.BasicHeader;
- import org.apache.http.protocol.HTTP;
- @SuppressWarnings("deprecation")
- public class HttpClientConnectionManager {
- /**
- * 获取SSL验证的HttpClient
- * @param httpClient
- * @return
- */
- @SuppressWarnings("deprecation")
- public static HttpClient getSSLInstance(HttpClient httpClient){
- ClientConnectionManager ccm = httpClient.getConnectionManager();
- SchemeRegistry sr = ccm.getSchemeRegistry();
- sr.register(new Scheme("https", MySSLSocketFactory.getInstance(), 443));
- httpClient = new DefaultHttpClient(ccm, httpClient.getParams());
- return httpClient;
- }
- /**
- * 模拟浏览器post提交
- *
- * @param url
- * @return
- */
- public static HttpPost getPostMethod(String url) {
- HttpPost pmethod = new HttpPost(url); // 设置响应头信息
- pmethod.addHeader("Connection", "keep-alive");
- pmethod.addHeader("Accept", "*/*");
- pmethod.addHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
- pmethod.addHeader("Host", "api.mch.weixin.qq.com");
- pmethod.addHeader("X-Requested-With", "XMLHttpRequest");
- pmethod.addHeader("Cache-Control", "max-age=0");
- pmethod.addHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0) ");
- return pmethod;
- }
- /**
- * 构建get方式的url
- *
- * @param reqUrl
- * 基础的url地址
- * @param params
- * 查询参数
- * @return 构建好的url
- */
- public static String httpPostWithJSON(String url, String json,String id)
- throws Exception {
- String result = null;
- // 将JSON进行UTF-8编码,以便传输中文
- String encoderJson = URLEncoder.encode(json, HTTP.UTF_8);
- DefaultHttpClient httpClient = new DefaultHttpClient();
- HttpPost httpPost = new HttpPost(url);
- httpPost.addHeader(HTTP.CONTENT_TYPE, "application/json");
- StringEntity se = new StringEntity(json);
- se.setContentType("application/json");
- se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,
- "UTF-8"));
- httpPost.setEntity(se);
- // httpClient.execute(httpPost);
- HttpResponse response = httpClient.execute(httpPost);
- if (response != null) {
- HttpEntity resEntity = response.getEntity();
- if (resEntity != null) {
- InputStream instreams = resEntity.getContent();
- ResourceBundle systemConfig = ResourceBundle.getBundle(
- "config/system", Locale.getDefault());
- String uploadSysUrl = systemConfig.getString("agentImgUrl")+id+"/";
- File saveFile = new File(uploadSysUrl+id+".jpg");
- // 判断这个文件(saveFile)是否存在
- if (!saveFile.getParentFile().exists()) {
- // 如果不存在就创建这个文件夹
- saveFile.getParentFile().mkdirs();
- }
- saveToImgByInputStream(instreams, uploadSysUrl, id+".jpg");
- }
- }
- return result;
- }
- /* @param instreams 二进制流
- * @param imgPath 图片的保存路径
- * @param imgName 图片的名称
- * @return
- * 1:保存正常
- * 0:保存失败
- */
- public static int saveToImgByInputStream(InputStream instreams,String imgPath,String imgName){
- int stateInt = 1;
- if(instreams != null){
- try {
- File file=new File(imgPath,imgName);//可以是任何图片格式.jpg,.png等
- FileOutputStream fos=new FileOutputStream(file);
- byte[] b = new byte[1024];
- int nRead = 0;
- while ((nRead = instreams.read(b)) != -1) {
- fos.write(b, 0, nRead);
- }
- fos.flush();
- fos.close();
- } catch (Exception e) {
- stateInt = 0;
- e.printStackTrace();
- } finally {
- }
- }
- return stateInt;
- }
- public void write(Object o, String path) {
- try {
- /* 创建存取文件 */
- FileOutputStream fileStream = new FileOutputStream(path);
- /* 将存取文件写入对象 */
- ObjectOutputStream os = new ObjectOutputStream(fileStream);
- /* 写入对象 */
- os.writeObject(o);
- System.out.println("写入数据成功");
- /* 关闭ObjectOutputStream */
- os.close();
- } catch (FileNotFoundException e) {
- e.printStackTrace();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- public static boolean exists(String imgPath){
- File saveFile = new File(imgPath);
- if (!saveFile.getParentFile().exists()) {
- return false;
- }else{
- //如果存在判断这个文件的大小
- if(saveFile.length()>0){
- System.out.println("--------------------------------"+saveFile.length());
- return true;
- }else{
- return false;
- }
- }
- }
- /**
- * 向指定URL发送GET方法的请求
- *
- * @param url
- * 发送请求的URL
- * @param param
- * 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
- * @return URL 所代表远程资源的响应结果
- */
- public static String sendGet(String url, String param) {
- String result = "";
- BufferedReader in = null;
- try {
- String urlNameString = url + "?" + param;
- System.out.println(urlNameString+"........");
- URL realUrl = new URL(urlNameString);
- // 打开和URL之间的连接
- 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));
- }
- // 定义 BufferedReader输入流来读取URL的响应
- 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块来关闭输入流
- finally {
- try {
- if (in != null) {
- in.close();
- }
- } catch (Exception e2) {
- e2.printStackTrace();
- }
- }
- return result;
- }
- public static void main(String[] args) {
- /*Map<String, Object> map = new HashMap<String,Object>();
- map.put("path", "pages/register");
- map.put("width", "430");*/
- String sendGet = sendGet("https://api.weixin.qq.com/cgi-bin/token", "grant_type=client_credential&secret=&appid=");
- System.out.println(sendGet);
- JSONObject json = JSONObject.fromObject(sendGet);
- String token = json.get("access_token").toString();
- System.out.println(token);
- /* String reqUrl = "https://api.weixin.qq.com/cgi-bin/token";
- *///sendGet(reqUrl, params)
- }
- }
tip
1、这是申请一张二维码的代码,申请多张可以用for或者其他的方法
2、当id为定量时,每次点击按钮判断filePath缓存是否存在,存在则直接取值展示,不存在则向后台请求二维码
3、重点提示步骤第三步获取的tonken是有有效期的,时长为2小时,2小时候需要重新请求一次tonken