分享功能生成小程序二维码

一、创建工具类HttpRequestUtil

/**
*生成小程序二维码工具类
*/
public class HttpRequestUtil {
	
	 /* 访问小程序获取数据的doGet方法
	 * @param url  要访问的地址
	 * @param param 访问的参数 
	 * @return
	 */
	 public static String doGet(String url, Map<String, String> param) {
		 
	        // 创建Httpclient对象
		    RequestConfig config = RequestConfig.custom().setConnectTimeout(60000).setSocketTimeout(60000).build();
		    
			CloseableHttpClient httpclient = HttpClientBuilder.create().setDefaultRequestConfig(config).build();
	      
	        String resultString = "";
	        CloseableHttpResponse response = null;
	        try {
	            // 创建uri
	            URIBuilder builder = new URIBuilder(url);
	            if (param != null) {
	                for (String key : param.keySet()) {
	                    builder.addParameter(key, param.get(key));
	                }
	            }
	            URI uri = builder.build();
	 
	            // 创建http GET请求
	            HttpGet httpGet = new HttpGet(uri);
	 
	            // 执行请求
	            response = httpclient.execute(httpGet);
	            // 判断返回状态是否为200
	            if (response.getStatusLine().getStatusCode() == 200) {
	                resultString = EntityUtils.toString(response.getEntity(), "UTF-8");
	            }
	        } catch (Exception e) {
	            e.printStackTrace();
	        } finally {
	            try {
	                if (response != null) {
	                    response.close();
	                }
	                httpclient.close();
	            } catch (IOException e) {
	                e.printStackTrace();
	            }
	        }
	        return resultString;
	    }
	 /**
	 *调用doGet方法
	 */
	    public static String doGet(String url) {
	        return doGet(url, null);
	    }
	 

	/**
	 * 根据小程序APPID和SECRET获取微信小程序token
	 * @param APPID 小程序APPID
	 * @param SECRET 小程序SECRET 
	 * @return
	 * @throws JSONException
	 */
	public static String getWxAccessToken(String APPID, String SECRET) throws JSONException {
		String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + APPID + "&secret=" + SECRET;
		String json = HttpRequestUtil.doGet(url);
		JSONObject obj = new JSONObject(json);
		return (String) obj.get("access_token");
	}

	/**
	 * 生成带参小程序二维码
	 *
	 * @param url 带token的小程序生成二维码地址
	 * @param paraMap 生成二维码的参数,是一个Map,存储要跳转的网页URL和二维码宽度等等
	 * @return
	 */
	public static byte[] getminiqrQr(String url, Map<String, Object> paraMap) throws Exception {
		byte[] result = null;
		HttpPost httpPost = new HttpPost(url);
		httpPost.addHeader("Content-Type", "application/json");
		// 设置请求的参数
		JSONObject postData = new JSONObject();
		for (Map.Entry<String, Object> entry : paraMap.entrySet()) {
			postData.put(entry.getKey(), entry.getValue());
		}
		httpPost.setEntity(new StringEntity(postData.toString(), "UTF-8"));
		HttpClient httpClient = HttpClientBuilder.create().build();
		HttpResponse response = httpClient.execute(httpPost);
		HttpEntity entity = response.getEntity();
		result = EntityUtils.toByteArray(entity);
		return result;

	}

	/**
	 * 下载带参小程序二维码
	 * @param response
	 * @param wxurl 要跳转的页面url
	 * @param width 生成二维码宽度
	 * @param APPID 小程序APPID
	 * @param SECRET 小程序SECRET 
	 * @throws Exception
	 */
	public static void downloadQrCode(HttpServletResponse response, String wxurl, int width, String APPID, String SECRET) throws Exception {
		//获取AccessToken
		String accessToken =getWxAccessToken(APPID, SECRET);
		byte[] qrCodeBytes = null;
		Map<String, Object> paraMap = new HashMap();
		String url = "https://api.weixin.qq.com/cgi-bin/wxaapp/createwxaqrcode?access_token=";
		url += accessToken;
		//二维码携带参数 不超过32位 参数类型必须是字符串
		paraMap.put("path", wxurl);  //存入的参数
		paraMap.put("width",width);
		qrCodeBytes=getminiqrQr(url,paraMap);
		response.setContentType("image/jpg");

		// 写入response的输出流中
		OutputStream stream = response.getOutputStream();
		stream.write(qrCodeBytes);
		stream.flush();
		stream.close();
	}
	    
}

二、创建Controller提供生成二维码接口

@Controller
@RequestMapping(value = "/share")
public class JobManagementController {
    //不同小程序的APPID和SECRET是不一样的,不要直接复制粘贴,然后就说不行
    public static final String APPID="wxac123456789154";
    public static final String SECRET="14521545dffjsdd5f45d4fds5f4sd1";
    
    /**
     * 生成岗位详情二维码
     */
    @GetMapping(value = "/code")
    public void policyCode(String uuid, HttpServletResponse response, HttpServletRequest request)  {
        try {
            String wxurl = "/wx/job/getJobInfo/" + uuid; //扫描二维码后要跳转的页面接口
            HttpRequestUtil.downloadQrCode(response,wxurl, 280, APPID, SECRET);
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值