1 import java.io.BufferedInputStream; 2 import java.io.File; 3 import java.io.FileOutputStream; 4 import java.net.URL; 5 import java.util.Date; 6 7 import javax.net.ssl.HttpsURLConnection; 8 9 import net.sf.json.JSONObject; 10 11 /** 12 * 二维码生成和读的工具类 13 * 14 */ 15 public class QRcode { 16 /** 17 * 永久二维码 18 * 19 * @param accessToken 20 * @param sceneId场景iD 1~10000 21 * @return 22 */ 23 public static String createForeverTicket(String accessToken, String barId) { 24 String ticke = null; 25 // 拼接请求地址 26 String requestUrl = "https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=TOKEN"; 27 requestUrl = requestUrl.replace("TOKEN", accessToken); 28 // 需要提交json数据 29 //String jsonmsg = "{\"action_name\": \"QR_LIMIT_STR_SCENE\",\"action_info\":{\"scene\":{\"scene_id\":%d}}}"; 30 String jsonmsg = "{\"action_name\": \"QR_LIMIT_STR_SCENE\", \"action_info\": {\"scene\": {\"scene_str\": \""+barId+"\"}}}"; 31 // 创建永久带参二维码 32 JSONObject jsonObject = WeixinUtil.httpRequest(requestUrl, "POST", String.format(jsonmsg, barId)); 33 if (null != jsonObject) { 34 try { 35 ticke = jsonObject.getString("ticket"); 36 System.out.println("永久带参二维码ticket成功=" + ticke); 37 } catch (Exception e) { 38 int err = jsonObject.getInt("errcode"); 39 String errormsg = jsonObject.getString("errmsg"); 40 System.out.println("永久带参二维码ticket失败失败errcode=" + err + "errmsg=" + errormsg); 41 } 42 } 43 return ticke; 44 } 45 46 public static String getRQcode(String ticket, String savepath) { 47 String filepath = null; 48 String requestUrl = "https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=TICKET"; 49 requestUrl = requestUrl.replace("TICKET", ticket); 50 try { 51 URL url = new URL(requestUrl); 52 HttpsURLConnection conn = (HttpsURLConnection) url.openConnection(); 53 conn.setDoInput(true); 54 conn.setRequestMethod("GET"); 55 if (!savepath.endsWith("/")) { 56 savepath += "/"; 57 } 58 // 将ticket 作为文件名 59 filepath = savepath + ticket + new Date().getTime() + ".jpg"; 60 // 将微信服务器返回的输入流写入文件 61 BufferedInputStream bis = new BufferedInputStream(conn.getInputStream()); 62 FileOutputStream fos = new FileOutputStream(new File(filepath)); 63 byte[] buf = new byte[8096]; 64 int size = 0; 65 while ((size = bis.read(buf)) != -1) 66 fos.write(buf, 0, size); 67 fos.close(); 68 bis.close(); 69 System.out.println(conn); 70 conn.disconnect(); 71 System.out.println("根据ticket换取二维码成功"); 72 } catch (Exception e) { 73 filepath = null; 74 System.out.println("根据ticket换取二维码失败" + e); 75 } 76 return filepath; 77 } 78 79 public static void main(String[] args) { 80 String assesstoken = WeixinUtil.getAccessToken(appid, secret); 81 String ticket = createForeverTicket(assesstoken, "你要携带的参数"); 82 String path = "d:/workspace/userfiles/ticket"; 83 getRQcode(ticket, path); 84 } 85 86 }
1 public static String getAccessToken(String appid, String secret) { 2 String accessTokenUrl = "https://api.weixin.qq.com/cgi-bin/token?" + "grant_type=client_credential" + 3 // 此处填写你自己的appid 4 "&appid=" + appid + 5 // 此处填写你自己的appsecret 6 "&secret=" + secret; 7 JSONObject jsonObject = httpUtils.httpsRequest(accessTokenUrl, "GET", null); 8 return (String) jsonObject.get("access_token"); 9 }
1 /** 2 * 发起https请求并获取结果 3 * 4 * @param requestUrl 请求地址 5 * @param requestMethod 请求方式(GET、POST) 6 * @param outputStr 提交的数据 7 * @return JSONObject(通过JSONObject.get(key)的方式获取json对象的属性值) 8*/ 9 public static JSONObject httpRequest(String requestUrl, String requestMethod, String outputStr) { 10 JSONObject jsonObject = null; 11 StringBuffer buffer = new StringBuffer(); 12 try { 13 // 创建SSLContext对象,并使用我们指定的信任管理器初始化 14 TrustManager[] tm = { new MyX509TrustManager() }; 15 SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE"); 16 sslContext.init(null, tm, new java.security.SecureRandom()); 17 // 从上述SSLContext对象中得到SSLSocketFactory对象 18 SSLSocketFactory ssf = sslContext.getSocketFactory(); 19 20 URL url = new URL(requestUrl); 21 HttpsURLConnection httpUrlConn = (HttpsURLConnection) url.openConnection(); 22 httpUrlConn.setSSLSocketFactory(ssf); 23 24 httpUrlConn.setDoOutput(true); 25 httpUrlConn.setDoInput(true); 26 httpUrlConn.setUseCaches(false); 27 // 设置请求方式(GET/POST) 28 httpUrlConn.setRequestMethod(requestMethod); 29 30 if ("GET".equalsIgnoreCase(requestMethod)) 31 httpUrlConn.connect(); 32 33 // 当有数据需要提交时 34 if (null != outputStr) { 35 OutputStream outputStream = httpUrlConn.getOutputStream(); 36 // 注意编码格式,防止中文乱码 37 outputStream.write(outputStr.getBytes("UTF-8")); 38 outputStream.close(); 39 } 40 41 // 将返回的输入流转换成字符串 42 InputStream inputStream = httpUrlConn.getInputStream(); 43 InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8"); 44 BufferedReader bufferedReader = new BufferedReader(inputStreamReader); 45 46 String str = null; 47 while ((str = bufferedReader.readLine()) != null) { 48 buffer.append(str); 49 } 50 bufferedReader.close(); 51 inputStreamReader.close(); 52 // 释放资源 53 inputStream.close(); 54 inputStream = null; 55 httpUrlConn.disconnect(); 56 jsonObject = JSONObject.fromObject(buffer.toString()); 57 } catch (ConnectException ce) { 58 log.error("Weixin server connection timed out."); 59 } catch (Exception e) { 60 log.error("https request error:{}", e); 61 } 62 return jsonObject; 63 }