长链接转短链接

2021年9月28日 2点热度 0条评论 来源: 弓长步又

一、使用场景

       二维码近几年超流行,有时项目中会使用到二维码,比如扫码登录后台。需要将字符串生成二维码,如果字符串太长,生成的二维码将会很难识别。此时就需要使用长链接转短链接。本文介绍使用微信长链接转短链接接口与新浪微博长链接转短链接接口。

二、代码实现

      因为长链接转短链接属于通用功能,所以外部项目会调用此功能,故以下代码是支持跨域调用的。

这里使用了jquery.jsonp-2.4.0.min.js,也可以使用ajax直接实现。

首先jsp引入jquery.jsonp-2.4.0.min.js,<script type="text/javascript" src="/js/jquery.jsonp-2.4.0.min.js"></script>

大家不用纠结其他业务代码,只关注如果转换就可以。

1、JSP页面如何调用

 //接收到二维码链接,生成二维码
                        //长链接转短链接后生成二维码
                        $.jsonp({
                            url: getShortUrl,
                            data: {longUrl: qrCodeLinkUrl},
                            callbackParameter: "callback",
                            success: function (data, textStatus, xOptions) {
                                console.log(data.shortUrl);
                                $('#code').qrcode(data.shortUrl);
                                //获取网页中的canvas对象
                                var myCanvas = document.getElementsByTagName('canvas')[0];
                                //将转换后的img标签插入到html中
                                $("#imgQrCode").attr("src", myCanvas.toDataURL("image/png"));
                            },
                            error: function (xOptions, textStatus) {
                                console.log("jsonp.error" + textStatus + ",rel=" + xOptions.data.longUrl)
                                $('#code').qrcode(qrCodeLinkUrl);
                                //获取网页中的canvas对象
                                var myCanvas = document.getElementsByTagName('canvas')[0];
                                //将转换后的img标签插入到html中
                                $("#imgQrCode").attr("src", myCanvas.toDataURL("image/png"));
                            }
                        });

2、控制器接收请求

                   /**
     * 长链接转短链接
     */
    @ResponseBody
    @RequestMapping(value = "/getShortUrl4Jsonp", method = {RequestMethod.GET, RequestMethod.POST})
    public String getShortUrl4Jsonp(HttpServletRequest request, @RequestParam(value = "longUrl", required = true) String longUrl, String callback) {
        logger.info("-----------长链接转短链接开始-----------");
        Long startTime = System.currentTimeMillis();
        logger.info("开始时间:" + startTime);
        //微信长链接转短链接接口每日调用上限1000,故先使用新浪微博获取
        String shortUrl = commonService.getShortUrlByWeiboApi(longUrl);
        //使用新浪微博转短链接失败后,使用微信长链接转短链接
        if (StringUtil.isEmpty(shortUrl)) {
	        //获取Spring.xml中配置的mpId
	        String mpId = ((WcGlobalVar) applicationContext.getBean("wcGlobalVar")).getInitKey();
	        try {
	            Mp mp = mpService.getMp(mpId);
	            String accessToken = mpService.getMpAccessToken(mp);
	            shortUrl = commonService.getShortUrl(accessToken, longUrl);
	            Map<String, String> jsonMap = new LinkedHashMap<>();
	            jsonMap.put("shortUrl", shortUrl);
	            jsonMap.put("longUrl", longUrl);
	            String jsonp = callback + "(" + JSON.toJSON(jsonMap) + ")";
            }
            Long endTime = System.currentTimeMillis();
            logger.info("结束时间:" + endTime);
            logger.info("耗时:" + (endTime - startTime));
            logger.info("-----------长链接转短链接结束-----------");
            return jsonp;

        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
    }

 

3、新浪微博长链接转短链接实现

/**
     * 新浪微博API长链接转短链接
     *	#新浪微博长链接转短链接请求地址
		 *	weibo.longToShortBaseUrl = http://api.weibo.com/2/short_url/shorten.json?source=APP_KEY&url_long=URL_LONG
		 *	#iPad新浪客户端App Key:2849184197 iphone新浪微博客户端 App Key:5786724301 Google.Nexus浪客户端App Key:1206405345 周博通微博管家App Key:202088835
		 *	weibo.appKey = 2849184197
     *
     */
    public String getShortUrlByWeiboApi(String longUrl) {
        String longToShortUrl = WcConfig.getInstance().getValue("weibo.longToShortBaseUrl")
                .replace("APP_KEY", WcConfig.getInstance().getValue("weibo.appKey"))
                .replace("URL_LONG", longUrl);
        String shortUrl = null;
        try {
            logger.info("getShortUrlByWeiboApi ---- 长链接地址:" + longUrl);
            String respJsonStr = HttpUtil.reqJsonGet(longToShortUrl);
            logger.info("getShortUrlByWeiboApi ---- 长链接地址响应" + respJsonStr);
            JSONObject respJson = JSONObject.parseObject(respJsonStr);
            JSONArray jsonArray = respJson.getJSONArray("urls");
            JSONObject respJO = jsonArray.getJSONObject(0);
            /*url_short	string	短链接    url_long	string	原始长链接  type	int	链接的类型,0:普通网页、1:视频、2:音乐、3:活动、5、投票 */
            String result = respJO.getString("result");
            String type = respJO.getString("type");
            logger.info("getShortUrlByWeiboApi ---- 长链接地址响应结果  result ----" + result + "-----" + type + "----url_long---" + respJO.getString("url_long") + "----url_short---" + respJO.getString("url_short"));
            if (StringUtil.equals("true", result)) {
                shortUrl = respJO.getString("url_short");
            } else {
                shortUrl = "";
            }
        } catch (Exception e) {
            e.printStackTrace();
            shortUrl = "";
        }
        return shortUrl;
    }

4、微信长链接转短链接实现

/**
     * 微信长链接换短链接
     * URL_SHORTURL = "https://api.weixin.qq.com/cgi-bin/shorturl?access_token=ACCESS_TOKEN";
     * @param accessToken
     * @param longUrl
     * @return
     */
    public String getShortUrl(String accessToken, String longUrl) {
        String shortUrl = "";
        String getShortUrl = WcGlobalVar.URL_SHORTURL.replace("ACCESS_TOKEN", accessToken);

        String reqJson = "{\"action\":\"long2short\",\"long_url\":\"" + longUrl + "\"}";
        logger.debug("返回json是:" + reqJson);
        //微信接口不支持http请求,调用接口使用https
        HttpUtils httpUtils = new HttpUtils();
        JSONObject respJson = httpUtils.doPostSSL(getShortUrl, reqJson);
        logger.debug("返回json是:" + respJson);
        if (respJson != null) {
            int errorCode = respJson.getInteger("errcode");
            String errorMessage = respJson.getString("errmsg");
            if (errorCode == 0) {
                shortUrl = respJson.getString("short_url");
            } else {
                logger.debug("长链接换短链接失败:错误代码:" + errorCode + ",错误原因:" + errorMessage);
                shortUrl = "";
            }
        }
        return shortUrl;
    }

5、http请求方法,请优先使用项目本身的HttpUtil工具类

 

public static String reqJsonGet(String url) throws MpExcepiton {
        log.debug("---do get http---");
        CloseableHttpClient httpClient = createSSLClientDefault();
        HttpGet get = new HttpGet(url);
        CloseableHttpResponse response;
        try {
            response = httpClient.execute(get);
            HttpEntity entity = response.getEntity();
            String respStr = EntityUtils.toString(entity, "UTF-8");
            EntityUtils.consume(entity);
            log.debug("do get, respStr="+respStr);
            if(null != respStr && !"".equals(respStr)){
                JSONObject jret = (JSONObject) JSONObject.parse(respStr);
                if(jret.containsKey("errcode")){
                    if(jret.get("errcode").equals("40029") || jret.get("errcode").equals("40001")){
                        throw new MpExcepiton(MpExcepiton.TokenInvalidHit,"httputil 访问微信资源");
                    }
                }
            }
            return respStr;
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            get.releaseConnection();
        }
        return "";
    }
/**
     * 发送 SSL POST 请求(HTTPS),JSON形式
     *
     * @param url       API接口URL
     * @param paramJson 请求数据
     * @return
     */
    public synchronized JSONObject doPostSSL(String url, String paramJson) {
        log.debug("---doPostSSL---");
        CloseableHttpClient httpClient = HttpClients.custom().setSSLSocketFactory(createSSLConnSocketFactory()).setConnectionManager(connMgr).setDefaultRequestConfig(requestConfig).build();
        HttpPost httpPost = new HttpPost(url);
        CloseableHttpResponse response = null;
        String httpStr = null;

        try {
            httpPost.setConfig(requestConfig);
            StringEntity stringEntity = new StringEntity(paramJson, "UTF-8");//解决中文乱码问题
            stringEntity.setContentEncoding("UTF-8");
            stringEntity.setContentType("application/json");
            httpPost.setEntity(stringEntity);
            log.debug("---即将httpClient.execute---URL------" + url + "-----------paramJson---------" + paramJson);
            response = httpClient.execute(httpPost);
            log.debug("Return status code =" + response.getStatusLine().getStatusCode());
            if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
                throw new RemoteServiceException(url, response.getStatusLine().getStatusCode(), null);
            }
            HttpEntity entity = response.getEntity();
            if (entity == null) {
                return null;
            }
            httpStr = EntityUtils.toString(entity, "utf-8");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (response != null) {
                try {
                    EntityUtils.consume(response.getEntity());
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return JSONObject.parseObject(httpStr);
    }

 

    原文作者:弓长步又
    原文地址: https://blog.csdn.net/biedazhangshu/article/details/81627294
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系管理员进行删除。