社区微信群开通啦,扫一扫抢先加入社区官方微信群
社区微信群
为了直接扫描一个二维码就进入小程序并完成部分业务操作, 需要用到微信小程序提供的二维码接口 wxacode.getUnlimited
在经历了一天的波折,算是初步完成功能了.
说几个注意事项,节省时间.
1. 请求方式为POST 地址为:https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=ACCESS_TOKEN
2. 请求参数为JSON
例如: {"scene"="value1","width":300}
3. 返回值有两种,错误时为JSON字符串 ,正确时为Buffer流.
错误代码如 {"errcode":47001,"errmsg":"data format error hint: [Tj00971523]"}
在获取TOKEN之后,替换请求地址中ACCESS_TOKEN.
随后,发送POST请求并获取流,代码如下:
/* 发送 post请求 用HTTPclient 发送请求*/
public byte[] post(String URL, String json) {
String obj = null;
InputStream inputStream = null;
Buffer reader = null;
byte[] data = null;
// 创建默认的httpClient实例.
CloseableHttpClient httpclient = HttpClients.createDefault();
// 创建httppost
HttpPost httppost = new HttpPost(URL);
httppost.addHeader("Content-type", "application/json; charset=utf-8");
httppost.setHeader("Accept", "application/json");
try {
StringEntity s = new StringEntity(json, Charset.forName("UTF-8"));
s.setContentEncoding("UTF-8");
httppost.setEntity(s);
CloseableHttpResponse response = httpclient.execute(httppost);
try {
// 获取相应实体
HttpEntity entity = response.getEntity();
if (entity != null) {
inputStream = entity.getContent();
data = readInputStream(inputStream);
}
return data;
} finally {
response.close();
}
} catch (Exception e) {
e.printStackTrace();
} finally {
// 关闭连接,释放资源
try {
httpclient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return data;
}
/** 将流 保存为数据数组
* @param inStream
* @return
* @throws Exception
*/
public static byte[] readInputStream(InputStream inStream) throws Exception {
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
// 创建一个Buffer字符串
byte[] buffer = new byte[1024];
// 每次读取的字符串长度,如果为-1,代表全部读取完毕
int len = 0;
// 使用一个输入流从buffer里把数据读取出来
while ((len = inStream.read(buffer)) != -1) {
// 用输出流往buffer里写入数据,中间参数代表从哪个位置开始读,len代表读取的长度
outStream.write(buffer, 0, len);
}
// 关闭输入流
inStream.close();
// 把outStream里的数据写入内存
return outStream.toByteArray();
}
之前我使用的是BufferedReader ,但写出的文件无法打开 ,我没有研究原因,希望有知道帅哥美女告诉一声.
String openid = "test";
String qrName = "session"+openid;
String Path = "D:\qrcode\"+qrName+".png";
String token = "你获取的token";
//你的json数据 ,格式不要错
String json = "{"scene":"name=jerry","width":300}";
byte[] data = http.post("https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token="+token,json);
//new一个文件对象用来保存图片
File imageFile = new File(Path);
//创建输出流
FileOutputStream outStream = null;
try {
outStream = new FileOutputStream(imageFile);
//写入数据
outStream.write(data);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
//关闭输出流
outStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
图片示例 :
如果觉得我的文章对您有用,请随意打赏。你的支持将鼓励我继续创作!