在java中先编写url请求的工具类:UrlUtil,代码如下:
package com.sinotrans.agent.basic.service.impl;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.URL;
import java.net.URLConnection;
import java.util.Iterator;
import java.util.Map;
public class UrlUtil {
/**
* 向指定 URL 发送POST方法的请求
*
* @param url
* 发送请求的 URL
* @param param
* 请求参数
* @return 所代表远程资源的响应结果
*/
public static String sendPost(String url, Map paramMap) {
PrintWriter out = null;
BufferedReader in = null;
String result = "";
String param = "";
Iterator it = paramMap.keySet().iterator();
while (it.hasNext()) {
String key = it.next();
param += key + "=" + paramMap.get(key) + "&";
}
try {
URL realUrl = new URL(url);
// 打开和URL之间的连接
URLConnection conn = realUrl.openConnection();
// 设置通用的请求属性
conn.setRequestProperty("accept", "*/*");
conn.setRequestProperty("connection", "Keep-Alive");
conn.setRequestProperty("Accept-Charset", "utf-8");
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(), "UTF-8"));
String line;
while ((line = in.readLine()) != null) {
result += line;
}
} catch (Exception e) {
System.out.println(e);
}
// 使用finally块来关闭输出流、输入流
finally {
try {
if (out != null) {
out.close();
}
if (in != null) {
in.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
return result;
}
}
然后编写获取token的方法,
public static String getToken() {
try {
Map map = new LinkedHashMap();
map.put("grant_type", "client_credential");
map.put("appid", "要链接到小程序的id");// 改成自己的appid
map.put("secret", "要链接小程序的secret"); //改成自己的secret
String rt = UrlUtil.sendPost("https://api.weixin.qq.com/cgi-bin/token", map);
JSONObject json = JSONObject.parseObject(rt);
if (json.getString("access_token") != null || json.getString("access_token") != "") {
System.out.println("token:" + json.getString("access_token"));
return json.getString("access_token");
} else {
return null;
}
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
接下来获取二维码的方法,为了测试,我将生成二维码流打印到了自己本地的D盘。看看能不能扫描成功,答案是可以:
//sceneStr:链接到改小程序界面所要的参数
//accessToken:上一个方法中所生产的token
public static Map getminiqrQr(String sceneStr, String accessToken) {
RestTemplate rest = new RestTemplate();
InputStream inputStream = null;
OutputStream outputStream = null;
try {
String url = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=" + accessToken;
Map param = new HashMap<>();
param.put("scene", sceneStr);
param.put("page", "pages/index/index");
param.put("width", 430);
param.put("auto_color", false);
MultiValueMap headers = new LinkedMultiValueMap<>();
HttpEntity requestEntity = new HttpEntity(param, headers);
ResponseEntity entity = rest.exchange(url, HttpMethod.POST, requestEntity, byte[].class,
new Object[0]);
System.out.println("调用小程序生成微信永久小程序码URL接口返回结果:" + entity.getBody());
byte[] result = entity.getBody();
inputStream = new ByteArrayInputStream(result);
File file = new File("D:/Desktop/3.png");
if (!file.exists()) {
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
outputStream = new FileOutputStream(file);
int len = 0;
byte[] in_b = null;
byte[] buf = new byte[1024];
while ((len = inputStream.read(buf, 0, 1024)) != -1) {
outputStream.write(buf, 0, len);
}
outputStream.flush();
} catch (Exception e) {
System.out.println("调用异常");
} finally {
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (outputStream != null) {
try {
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return null;
}
添加main方法测试:
public static void main(String[] args) {
String token = getToken();
getminiqrQr("1023", token);
}
获取token,二维码的方法,以及测试的main方法,放到一个类中即可,复制可运行,但得导入相应的jar包。
这就生成二维码了,具体获取token.二维码的参数,可以到小程序官网进行查看,此测试只填写了必须的参数。
(小程序获取二维码官网:https://developers.weixin.qq.com/miniprogram/dev/api-backend/open-api/access-token/auth.getAccessToken.html
获取token:https://developers.weixin.qq.com/miniprogram/dev/api-backend/open-api/access-token/auth.getAccessToken.html)