调用百度API去生成短链接

 
        /// 
        /// 发送HTTP请求
        /// 
        /// 请求的URL
        /// 请求的参数
        /// 请求结果
        public static string RequestBaiduAPIStore(string url, string param)
        {
            string strURL = url;
            string strValue = "";

            try
            {
                System.Net.HttpWebRequest request;
                request = (System.Net.HttpWebRequest)WebRequest.Create(strURL);
                request.Method = "POST";
                // 添加header
                request.Headers.Add("apikey", "41ab8c3a"); //您自己的apikey: 41ab8c3a 
                request.ContentType = "application/x-www-form-urlencoded";
                string paraUrlCoded = param;
                byte[] payload;
                payload = System.Text.Encoding.UTF8.GetBytes(paraUrlCoded);
                request.ContentLength = payload.Length;
                Stream writer = request.GetRequestStream();
                writer.Write(payload, 0, payload.Length);
                writer.Close();
                System.Net.HttpWebResponse response;
                response = (System.Net.HttpWebResponse)request.GetResponse();
                System.IO.Stream s;
                s = response.GetResponseStream();
                string StrDate = "";

                StreamReader Reader = new StreamReader(s, Encoding.UTF8);
                while ((StrDate = Reader.ReadLine()) != null)
                {
                    strValue += StrDate + "\r\n";
                }
            }
            catch (Exception ex)
            {

            }

            return strValue;
        }

调用样例:


string url = "http://apis.baidu.com/3023/shorturl/shorten";
            string param = "url_long=" + HttpUtility.UrlEncode("http://www.baidu.com");
            //"url_long=http%3A%2F%2Fapistore.baidu.com%2Fastore%2Fshopready%2F1973.html";
            // http://t.cn/RUOn4qB

string sResult = Gbi.Extensions.RequestBaiduAPIStore(url, param);

string sShortLink = Gbi.Extensions.GetJsonNodeValue("urls", sResult);
if (!string.IsNullOrEmpty(sShortLink))
{
    sShortLink = Gbi.Extensions.GetJsonNodeValueFromFirstArrayItem("url_short", sShortLink);
    sResult = sShortLink;
}


你可能感兴趣的:(调用百度API去生成短链接)