日期:2014-05-18 浏览次数:21009 次
/// <summary> /// 调用Google API 生成短网址 /// </summary> /// <param name="longUrl">长地址</param> /// <returns>短网址</returns> public static string GetShortUrl(string longUrl) { CookieContainer cc = new CookieContainer(); string url = "http://goo.gl/api/shorten"; HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); request.Method = "POST"; request.ContentType = "application/x-www-form-urlencoded"; request.CookieContainer = cc; string data = "url=" + HttpUtility.UrlEncode(longUrl) + "&security_token="; request.ContentLength = data.Length; StreamWriter writer = new StreamWriter(request.GetRequestStream(), Encoding.ASCII); writer.Write(data); writer.Flush(); HttpWebResponse response = (HttpWebResponse)request.GetResponse(); string encoding = response.ContentEncoding; if (encoding == null || encoding.Length < 1) { encoding = "utf-8"; //默认编码 } StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding(encoding)); data = reader.ReadToEnd(); response.Close(); return data; }