赞
踩
public class Qrutil { public static String postToken(String appId,String appKey) throws Exception{ String requestUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="+appId+"&secret="+appKey; URL url = new URL(requestUrl); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("POST"); connection.setRequestProperty("Content-Type","application/json"); connection.setRequestProperty("Connection","Keep-Alive"); connection.setUseCaches(false); connection.setDoInput(true); connection.setDoOutput(true); //得到请求的输出流对象 DataOutputStream out = new DataOutputStream(connection.getOutputStream()); out.writeBytes(""); out.flush(); out.close(); //建立实际的链接 connection.connect(); //定义bufferdreader输入流来读取url的响应 BufferedReader in; if(requestUrl.contains("nIp")){ in = new BufferedReader(new InputStreamReader(connection.getInputStream(),"GBK")); }else { in = new BufferedReader(new InputStreamReader(connection.getInputStream(),"UTF-8")); } StringBuilder result = new StringBuilder(); String getLine; while ((getLine=in.readLine())!=null){ result.append(getLine); } in.close(); JSONObject jsonObject = new JSONObject(result.toString()); return jsonObject.getStr("access_token"); } public static void generateQrCode(String filePath,String page,String scene,String accessToken){ try{ //调用微信接口生成二维码 URL url = new URL("https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token="+accessToken); HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection(); httpURLConnection.setRequestMethod("POST"); httpURLConnection.setConnectTimeout(10000); httpURLConnection.setReadTimeout(2000); httpURLConnection.setDoOutput(true); httpURLConnection.setDoInput(true); PrintWriter printWriter = new PrintWriter(httpURLConnection.getOutputStream()); //发送请求参数 JSONObject paramJson = new JSONObject(); //二维码里携带的参数 paramJson.put("scene",scene); //该接口传入的是page而不是path paramJson.put("page",page); //扫描二维码后跳转的页面 paramJson.put("width",200); paramJson.put("is_hyaline",true); paramJson.put("auto_color",true); //要打开的小程序版本。正式版为 "release",体验版为 "trial",开发版为 "develop"。默认是正式版。 paramJson.put("env_version","develop"); printWriter.write(paramJson.toString()); //flush输出流缓冲 printWriter.flush(); //开始获取数据 BufferedInputStream bis = new BufferedInputStream(httpURLConnection.getInputStream()); OutputStream os = new FileOutputStream(new File(filePath)); int len; byte[] arr = new byte[1024]; while ((len = bis.read(arr))!=-1){ os.write(arr,0,len); os.flush(); } os.close(); }catch (Exception e){ e.printStackTrace(); } } }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。