小程序 获取二维码 java方式

本人也是初学者有不对的地方欢迎指出.所有自己总结一下希望能帮到大家!
我尝试了两种方式后去小程序二维码,
第一种 前台请求获取的方式 用的都是B接口 注意:这个接口只有项目上线了才能扫出来
在这里插入图片描述
调用这个接口前你需要获取access_token 凭证

在这里插入图片描述
这几个必要条件
在这里插入图片描述
一般都是放在后台去请求我用的是Java , 我工具类和调用 我是在别人的基础上加了自己的方法,工具类需要根据自己的要求做修改.
在这里插入图片描述

工具类 调用getminiqrQr的时候需要根据自己的情况修改下 其他的不用

package com.esmall.utils;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;
import java.util.Map;

import javax.imageio.ImageIO;

import com.esmall.core.common.CommonConstants;
import com.esmall.core.common.Constants;
import com.qq.connect.utils.json.JSONObject;

public class HttpRequest {

public static void main(String[] args) {
	// 发送 GET 请求
	String s = HttpRequest.sendGet("http://v.qq.com/x/cover/kvehb7okfxqstmc.html?vid=e01957zem6o", "");
	System.out.println(s);

	// //发送 POST 请求
	// String
	// sr=HttpRequest.sendPost("http://www.toutiao.com/stream/widget/local_weather/data/?city=%E4%B8%8A%E6%B5%B7",
	// "");
	// JSONObject json = JSONObject.fromObject(sr);
	// System.out.println(json.get("data"));
}

/**
 * 向指定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;
		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;
}

/**
 * 向指定 URL 发送POST方法的请求
 * 
 * @param url
 *            发送请求的 URL
 * @param param
 *            请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
 * @return 所代表远程资源的响应结果
 */
public static String sendPost(String url, String param) {
	PrintWriter out = null;
	BufferedReader in = null;
	String result = "";
	try {
		URL realUrl = new URL(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)");
		// 发送POST请求必须设置如下两行
		conn.setDoOutput(true);
		conn.setDoInput(true);
		// 获取URLConnection对象对应的输出流
		out = new PrintWriter(conn.getOutputStream());
		// 发送请求参数
		out.print(param);
		// flush输出流的缓冲
		out.flush();
		// 定义BufferedReader输入流来读取URL的响应
		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块来关闭输出流、输入流
	finally {
		try {
			if (out != null) {
				out.close();
			}
			if (in != null) {
				in.close();
			}
		} catch (IOException ex) {
			ex.printStackTrace();
		}
	}
	return result;
}

/**
 * 生成带参小程序二维码
 * 
 * @param sceneStr
 *            参数 
 * @param accessToken
 *            token
 */
public static String getminiqrQr(String sceneStr, String accessToken,) {
	String result = "";
	try {
		URL url = new URL("https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=" + accessToken);
		HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
		httpURLConnection.setRequestMethod("POST");// 提交模式
		// 设置通用的请求属性
		// httpURLConnection.setRequestProperty("content-type",
		// "application/json");
		httpURLConnection.setRequestProperty("accept", "*/*");
		httpURLConnection.setRequestProperty("connection", "Keep-Alive");
		httpURLConnection.setRequestProperty("user-agent",
				"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
		// conn.setConnectTimeout(10000);//连接超时 单位毫秒
		// conn.setReadTimeout(2000);//读取超时 单位毫秒
		// 发送POST请求必须设置如下两行
		httpURLConnection.setDoOutput(true);
		httpURLConnection.setDoInput(true);
		// 获取URLConnection对象对应的输出流
		PrintWriter printWriter = new PrintWriter(httpURLConnection.getOutputStream());
		// 发送请求参数   这里根据自己的需要 
		JSONObject paramJson = new JSONObject();
		paramJson.put("scene", sceneStr);
		// paramJson.put("page", "pages/index/index");
		paramJson.put("width", 430);
		// paramJson.put("auto_color", true);
		/**
		 * line_color生效 paramJson.put("auto_color", false); JSONObject
		 * lineColor = new JSONObject(); lineColor.put("r", 0);
		 * lineColor.put("g", 0); lineColor.put("b", 0);
		 * paramJson.put("line_color", lineColor);
		 */

		printWriter.write(paramJson.toString());
		// flush输出流的缓冲
		printWriter.flush();
		BufferedInputStream bis = new BufferedInputStream(httpURLConnection.getInputStream());
		String originalFilename = null;
		// 二维码的地址
		String url = ""; // 需要存放的文件路径
		File file = new File("");//这里的是路径写到你要放的文件夹那层就可以了 没有就会创建
		if(!file.exists()){
			file.mkdirs();
		}
		OutputStream os = new FileOutputStream(new File(url));
		// FileUtils.copyInputStreamToFile(myfile.getInputStream(), new
		// File(realPath, originalFilename));
		int len;
		byte[] arr = new byte[1024];
		while ((len = bis.read(arr)) != -1) {
			os.write(arr, 0, len);
			os.flush();
		}
		os.close();
		
		result = 返回二维码路径地址;
	} catch (Exception e) {
		e.printStackTrace();
	}
	return result;
}

}

这个是调用的方法

/**
* 二维码生成扫描
*
* @throws JSONException
*
*/
@RequestMapping(value = “/thinkChange”)
@ResponseBody
public Map<String, Object> thinkChange(
@RequestParam(required = false, value = “wechatId”, defaultValue = “”) String wechatId,
@RequestParam(required = false, value = “memberId”, defaultValue = “”) String memberId)
throws JSONException {
Map<String, Object> map = Maps.newHashMap();
// 小程序唯一标识 填写自己的
String wxspAppid = “”;
// app secret 填写自己的
String wxspSecret = “”;
// 二维码参数值
String paramss = “grant_type=client_credential&appid=” + wxspAppid + “&secret=” + wxspSecret;
// 生成二维吗的 access_token 值
String srs = HttpRequest.sendGet(“https://api.weixin.qq.com/cgi-bin/token”, paramss);
// 解析相应内容(转换成json对象)
JSONObject json = new JSONObject(srs);
// 获取accessToken的凭证
String accessToken = json.get(“access_token”).toString();
String scene = “”;
// 二维码接口
String getminiqrQr = HttpRequest.getminiqrQr(scene, accessToken);

		map.put("qrQr", getminiqrQr);

	    System.out.print(map);
	return map;

}

还有一种js直接调用 我是看了下面这个人的博客 是可以实现的 传送门
https://blog.csdn.net/qq_41473887/article/details/81335977
我用上面的方法实现了 我碰到了个问题是 就是需要请求两次才能把生成二维码.我也不知道什么原因.
在这里插入图片描述

对了 因为我用的是Java后台下载本地了 要给用户一个点击下载到相册

//将图片保存到相册
wx.downloadFile({
url: scanLife,
success: function(res) {
//图片保存到本地
wx.saveImageToPhotosAlbum({
filePath: res.tempFilePath,
success: function(data) {
wx.hideLoading()
wx.showModal({
title: ‘提示’,
content: ‘您的推广海报已存入手机相册,赶快分享给好友吧’,
showCancel: false,
})
},
fail: function(err) {
if (err.errMsg === “saveImageToPhotosAlbum:fail:auth denied” || err.errMsg === “saveImageToPhotosAlbum:fail auth deny”) {
// 这边微信做过调整,必须要在按钮中触发,因此需要在弹框回调中进行调用
wx.showModal({
title: ‘提示’,
content: ‘需要您授权保存相册’,
showCancel: false,
success: modalSuccess => {
wx.openSetting({
success(settingdata) {
console.log(“settingdata”, settingdata)
if (settingdata.authSetting[‘scope.writePhotosAlbum’]) {
wx.showModal({
title: ‘提示’,
content: ‘获取权限成功,再次点击图片即可保存’,
showCancel: false,
})
} else {
wx.showModal({
title: ‘提示’,
content: ‘获取权限失败,将无法保存到相册哦~’,
showCancel: false,
})
}
},
fail(failData) {
console.log(“failData”, failData)
},
complete(finishData) {
console.log(“finishData”, finishData)
}
})
}
})
}
},
complete(res) {
wx.hideLoading()
}
})
},
fail: function (err){

   }
})

这个是接口调试 可以知道你的接口是不是有用
https://mp.weixin.qq.com/debug/cgi-bin/apiinfo?t=index&type=基础支持&form=获取access_token接口 /token

写的比较乱 见谅 有意见可以提出 我会改修改 应为上面的只是一个大概按自己的情况修改,
借鉴了很多别人的博客 谢谢大神!

你可以使用企业微信提供的API来获取小程序二维码。以下是Java代码示例: ```java import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.URL; public class GetQrcode { public static void main(String[] args) { String accessToken = "YOUR_ACCESS_TOKEN"; // 替换为实际的access_token String path = "https://qyapi.weixin.qq.com/cgi-bin/wxaapp/createwxaqrcode?access_token=" + accessToken; String params = "{\"path\":\"pages/index/index\",\"width\":430}"; try { URL url = new URL(path); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setDoOutput(true); conn.setDoInput(true); conn.setRequestMethod("POST"); conn.setRequestProperty("Content-Type", "application/json"); conn.setUseCaches(false); conn.setInstanceFollowRedirects(true); conn.connect(); // 将参数写入请求体 byte[] data = params.getBytes(); conn.getOutputStream().write(data); conn.getOutputStream().flush(); conn.getOutputStream().close(); // 读取响应 InputStream is = conn.getInputStream(); byte[] buffer = new byte[1024]; int len = 0; FileOutputStream fos = new FileOutputStream("qrcode.jpg"); while ((len = is.read(buffer)) != -1) { fos.write(buffer, 0, len); } fos.close(); is.close(); conn.disconnect(); System.out.println("二维码已保存至本地!"); } catch (IOException e) { e.printStackTrace(); } } } ``` 在代码中替换`YOUR_ACCESS_TOKEN`为实际的access_token,同时指定小程序路径和二维码宽度,即可获取小程序二维码并保存至本地。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值