您的位置:首页 > 编程语言 > C#

博客开发手记1 – 不能发布URL长度超过280字符微博的解决方案(C#实现)

2010-12-24 14:20 691 查看
开发微博PPC客户端时发现,不能发布URL长度超过280字符的微博(网页端也有此问题),例如发布一个淘宝商品图片:URL http://www.taobao.com/view_image.php?pic=Wx0GGlFDXA1VUwMFWx0SCwkNGRFcVxxQW1UcCxMFRBkDCFdVV1cRRhpTRDhHQghddWtdVEAxKgtSA0MHZ2sDBUBfRlJFBgYV&title=zeLDs8zYvNvP5LD8ILH2usBCSU5IQU%2FV%2Fca3IMLD0NDP5C%2B1x7v6z%2BQvzdDUy8%2FkL8CtuMvP5DI0tOc%3D&version=2&c=OTgzMDkyZWY2Njk3MjI4ZmI2ZGUzMjdlYTkyODEyOTI%3D&itemId=85a8fa3ca3d4933e7e6d57714c28105a&dbId=db1&fv=9

直接将此URL输入到信息框,将提示信息超出长度,如下图:



WeGo(微博PPC客户端)



新浪微博网页端

使用WeGo的URL短地址编辑器即可实现发布此微博,具体操作如下:

1.进入短地址编辑界面



2.输入要缩短的URL,点击"确定"



3.生成短地址,发布微博



具体解决方案如下:

使用ShortText.com 或 TinyURL.com等短地址生成网站的API生成短地址,然后使用短地址发布微博。
本文以ShortText.com API为例,使用C#实现,具体实现如下:

public class ShortTextURL
{
private const string APIURL = "http://shortText.com/api.aspx";

public string GetShortenedText(string inputText)
{
string data = "shorttext=" + HttpUtility.UrlEncode(inputText);
const int trimLength = 5;
string shortenURL = ExecutePostCommand(APIURL, data);
if (!string.IsNullOrEmpty(shortenURL))
{
string newText =
inputText.Substring(0, inputText.LastIndexOf(" ", 140 - (shortenURL.Length + trimLength))) + " " +
shortenURL;
return newText;
}
return inputText;
}

private static string ExecutePostCommand(string url, string data)
{
var request = CreateHttpRequest(new Uri(url));

request.ContentType = "application/x-www-form-urlencoded";
request.Method = "POST";
request.Timeout = 20000;

byte[] bytes = Encoding.UTF8.GetBytes(data);

request.ContentLength = bytes.Length;
try
{
using (var requestStream = request.GetRequestStream())
{
requestStream.Write(bytes, 0, bytes.Length);
requestStream.Flush();
}
}
catch (Exception)
{

}

try
{
using (var response = (HttpWebResponse)request.GetResponse())
{
using (var reader = new StreamReader(response.GetResponseStream()))
{
return reader.ReadToEnd();
}
}
}
catch (WebException ex)
{
System.Diagnostics.Debug.WriteLine(ex.Message);
}
return null;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐