微信长连接转短连接

        /// 
        /// 微信长链接转短链接
        /// 
        /// 
        public string GetShortUrl()
        {
            //参数            是否必须             说明
            //access_token      是                 调用接口凭证
            //action            是                 此处填long2short,代表长链接转短链接
            //long_url          是                 需要转换的长链接,支持http://、https://、weixin://wxpay 格式的url

            string ACCESS_TOKEN = "此处是自己生成的token";
            //微信请求地址
            string url = "https://api.weixin.qq.com/cgi-bin/shorturl?access_token=" + ACCESS_TOKEN;

            //请求的json参数
            string data = "{\"action\":\"long2short\",\"long_url\":\"https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxdcf95956728d02b2&redirect_uri=http://testwx.hanorunion.com/Home/Login3?companyid=1&response_type=code&scope=snsapi_userinfo&state=123#wechat_redirect\"}";

            string ret = string.Empty;
            try
            {
                byte[] byteArray = System.Text.Encoding.UTF8.GetBytes(data); //转化
                HttpWebRequest webReq = (HttpWebRequest)WebRequest.Create(new Uri(url));
                webReq.Method = "POST";
                webReq.ContentType = "application/json";

                webReq.ContentLength = byteArray.Length;
                Stream newStream = webReq.GetRequestStream();
                newStream.Write(byteArray, 0, byteArray.Length);//写入参数
                newStream.Close();
                HttpWebResponse response = (HttpWebResponse)webReq.GetResponse();
                var ce = response.ContentEncoding;
                StreamReader sr = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding("UTF-8"));
                ret = sr.ReadToEnd();

                sr.Close();
                response.Close();
                newStream.Close();
            }
            catch (Exception ex)
            {

            }

            //正常情况下,微信会返回下述JSON数据包给公众号:
            //{"errcode":0,"errmsg":"ok","short_url":"http:\/\/w.url.cn\/s\/AvCo6Ih"}

            string errcode = "";//错误码。
            string errmsg = "";//错误信息。
            string short_url = "";//短链接。

            //解析响应信息
            if (string.IsNullOrWhiteSpace(ret))
            {
                JObject jo = (JObject)JsonConvert.DeserializeObject(ret);
                errcode = jo["errcode"].ToString();//错误码。
                errmsg = jo["errmsg"].ToString();//错误信息。
                short_url = jo["short_url"].ToString();//短链接。
            }

            return short_url;
        }

你可能感兴趣的:(c#,微信,微信,C#,长连接转短连接)