1. 程式人生 > >java生成小程式二維碼

java生成小程式二維碼

直接上程式碼

public class XcxQRCode {
	
	static String  APPID = "";//自己的appid
	static String  SECRET = "";
	/**
	 * 生成二維碼
	 * Folder:資料夾路徑
	 * xcxUrl:小程式地址 必須已釋出的小程式
	 * @param Folder
	 * @param xcxUrl
	 * @return
	 */
	public static Object QRCode(String Folder,String xcxUrl) {
			
		String ACCESS_TOKEN = GetACCESS_TOKEN();//獲取ACCESS_TOKEN
		String name = GetQRCode(ACCESS_TOKEN,Folder,xcxUrl,300);
		System.out.println(name);
		return name;
	}
	
	public static String GetACCESS_TOKEN() {
		String requestStr = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=SECRET";
		requestStr = requestStr.replace("APPID",  APPID);
		requestStr = requestStr.replace("SECRET",SECRET);
		String oauth2_Token = HttpXmlClient.get(requestStr);
		JSONObject jsonObject = new JSONObject();
		jsonObject = JSONObject.fromObject(oauth2_Token);
		return jsonObject.getString("access_token");
	}
	
	public static String GetQRCode(String ACCESS_TOKEN,String Folder,String xcxPath,int width) {
		String createwxaqrcodeStr = "https://api.weixin.qq.com/cgi-bin/wxaapp/createwxaqrcode?access_token="+ACCESS_TOKEN;
		InputStream is = PostInputStream(createwxaqrcodeStr, "{\"path\":\""+xcxPath+"\",\"width\":"+width+"}");
		String name = new Date().getTime()+".png";
		int i = saveToImgByInputStream(is, Folder, name);
		if(i==1) {
			return Folder+"/"+name;
		}
		try {
			return null;
		}  catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}
	 /** 
     * 傳送HttpPost請求 返回流
     *  
     * @param strURL 
     *            服務地址 
     * @param params 
     *            json字串,例如: "{ \"id\":\"12345\" }" ;其中屬性名必須帶雙引號<br/> 
     * @return 成功:返回json字串<br/> 
     */  
    public static InputStream PostInputStream(String strURL, String params) {  
        try {  
            URL url = new URL(strURL);// 建立連線  
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();  
            connection.setDoOutput(true);  
            connection.setDoInput(true);  
            connection.setUseCaches(false);  
            connection.setInstanceFollowRedirects(true);  
            connection.setRequestMethod("POST"); // 設定請求方式  
            connection.setRequestProperty("Accept", "application/json"); // 設定接收資料的格式  
            connection.setRequestProperty("Content-Type", "application/json"); // 設定傳送資料的格式  
            connection.connect();  
            OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream(), "UTF-8"); // utf-8編碼  
            out.append(params);  
            out.flush();  
            out.close();  
            InputStream is = connection.getInputStream();  
            return is;
            
        } catch (IOException e) {  
              
            e.printStackTrace();  
        }  
        return null; // 自定義錯誤資訊  
    }  
    /**
     * 將二進位制轉換成檔案儲存
     * @param instreams 二進位制流
     * @param imgPath 圖片的儲存路徑
     * @param imgName 圖片的名稱
     * @return 
     *      1:儲存正常
     *      0:儲存失敗
     */
    public static int saveToImgByInputStream(InputStream instreams,String imgPath,String imgName){
        int stateInt = 1;
        if(instreams != null){
            try {
            	createDir(imgPath);
                File file=new File(imgPath,imgName);//可以是任何圖片格式.jpg,.png等
                FileOutputStream fos=new FileOutputStream(file);
                byte[] b = new byte[1024];
                int nRead = 0;
                while ((nRead = instreams.read(b)) != -1) {
                    fos.write(b, 0, nRead);
                }
                fos.flush();
                fos.close();                
            } catch (Exception e) {
                stateInt = 0;
                e.printStackTrace();
            } finally {
            }
        }
        return stateInt;
    }
    /**
	 * 建立資料夾
	 * 
	 * @param destDirName
	 * @return
	 */
	public static boolean createDir(String destDirName) {
		try {
			destDirName = URLDecoder.decode(destDirName, "GB2312");
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		File dir = new File(destDirName);
		if (dir.exists()) {
			System.out.println("建立目錄" + destDirName + "失敗,目標目錄已經存在");
			return false;
		}
		if (!destDirName.endsWith(File.separator)) {
			destDirName = destDirName + File.separator;
		}
		// 建立目錄
		if (dir.mkdirs()) {
			System.out.println("建立目錄:" + destDirName + "成功!");
			return true;
		} else {
			System.out.println("建立目錄:" + destDirName + "失敗!");
			return false;
		}
	}
    
	public static void main(String[] args) {
		QRCode("d:/","pages/index/index");
	}
}

HttpXmlClient.util

public class HttpXmlClient {
	private static Logger log = Logger.getLogger(HttpXmlClient.class);  
    /**
     * 返回請求介面回覆的json資料
     * @param url
     * @param params
     * @return
     */
    public static String post(String url, Map<String, String> params) { 
    	
		DefaultHttpClient httpclient = new DefaultHttpClient();  
        String body = null;  
          
        log.info("create httppost:" + url);  
        HttpPost post = postForm(url, params);  
        body = invoke(httpclient, post); 
        httpclient.getConnectionManager().shutdown();  
        return body;  
    }  
      
    public static String get(String url) {  
        DefaultHttpClient httpclient = new DefaultHttpClient();  
        String body = null;  
          
        log.info("create httpget:" + url);  
        HttpGet get = new HttpGet(url);  
//        get.setProtocolVersion(HttpVersion.HTTP_1_0);
        body = invoke(httpclient, get);  
          
        httpclient.getConnectionManager().shutdown();  
          
        return body;  
    }  
          
      
    private static String invoke(DefaultHttpClient httpclient,  
            HttpUriRequest httpost) {  
        HttpResponse response = sendRequest(httpclient, httpost);  
        String body = paseResponse(response);  
        return body;  
    }  
  
    private static String paseResponse(HttpResponse response) {  
        log.info("get response from http server..");  
        HttpEntity entity = response.getEntity();  
          
        log.info("response status: " + response.getStatusLine());  
        String charset = EntityUtils.getContentCharSet(entity);  
        log.info(charset);  
          
        String body = null;  
        try {  
            body = EntityUtils.toString(entity);  
            log.info(body);  
        } catch (ParseException e) {  
            e.printStackTrace();  
        } catch (IOException e) {  
            e.printStackTrace();  
        }  
          
        return body;  
    }  
  
    private static HttpResponse sendRequest(DefaultHttpClient httpclient,  
            HttpUriRequest httpost) {  
        log.info("execute post...");  
        HttpResponse response = null;  
        try {  
            response = httpclient.execute(httpost);  
        } catch (ClientProtocolException e) {  
            e.printStackTrace();  
        } catch (IOException e) {  
            e.printStackTrace();  
        }  
        return response;  
    }  
  
    private static HttpPost postForm(String url, Map<String, String> params){  
          
        HttpPost httpost = new HttpPost(url);  
        List<NameValuePair> nvps = new ArrayList <NameValuePair>();  
        
        if (params == null) {
			return httpost;
		}
        else
        {
	        Set<String> keySet = params.keySet();
	        
	        for(String key : keySet) {  
	            nvps.add(new BasicNameValuePair(key, params.get(key)));  
	        }  
	        try {  
	            log.info("set utf-8 form entity to httppost");  
	            httpost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));  
	        } catch (UnsupportedEncodingException e) {  
	            e.printStackTrace();  
	        }  
	          
	        return httpost;  
        }
    }  
}