案例:客户签收后,系统会回复一条短信给客户及一个点评服务的链接,由于链接过长,短信会自动截断,所以使用短链的方式发送。
代码如下:
public string GetTinyUrl(string strLongUrl)
{
try
{
byte[] postData = Encoding.UTF8.GetBytes("url=" + strLongUrl);
var url = "http://dwz.cn/create.php";
var client = new WebClient();
client.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
byte[] responseData = client.UploadData(url, "POST", postData);
var result = Encoding.UTF8.GetString(responseData);
IDictionary<string, string> dicResult = ParseSinge(result);
return dicResult["tinyurl"].Replace("\\", "");
}
catch (Exception)
{
return "";
}
}
/// <summary>
/// 解析JSON字符串
/// </summary>
/// <param name="pJsonStr">待解析的字符串形如:[{...,...,...}]</param>
/// <returns>返回数据集合</returns>
public IDictionary<string, string> ParseSinge(string pJsonStr)
{
if (pJsonStr.Trim().Length == 0 || pJsonStr.IndexOf("{") == -1 || pJsonStr.IndexOf("}") == -1) return null;
System.Text.StringBuilder sb = new System.Text.StringBuilder(pJsonStr);
//去除[{和}]
sb.Remove(0, 1);
sb.Remove(sb.Length - 1, 1);
string[] arr = sb.ToString().Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries);
if (arr == null || arr.Length == 0) return null;
//解析键值对
Dictionary<string, string> dic = new Dictionary<string, string>();
string[] brr = null;
foreach (string str in arr)
{
brr = str.Split(new char[] { ‘:‘ }, 2);
dic.Add(brr[0].Replace("\"",""), brr[1].Replace("\"",""));
}
return dic;
}
以上为生成短URL代码,希望对大家有所帮助。 更多.net教程:net.itcast.cn/net/video.shtml
本文出自 “书海世界” 博客,请务必保留此出处http://10221941.blog.51cto.com/10211941/1650053
原文地址:http://10221941.blog.51cto.com/10211941/1650053