本文介绍了Nuget包,用于缩短链接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要使用C#来缩短链接。是否有任何nuget软件包?
可以有人提供我的代码以便我使用它吗。
I need to shorten my links using bitly in C#. Is there any nuget package for this?Can some one provide me code for that so that I can use that.
推荐答案
签出或只是自己调用该位。 ly API。该API非常易于使用和使用。
Check out https://www.nuget.org/packages/BitlyAPI/ or just make your own call to the bit.ly api. The api is very easy to use and work with.
public string Shorten(string longUrl, string login, string apikey)
{
var url = string.Format("http://api.bit.ly/shorten?format=json&version=2.0.1&longUrl={0}&login={1}&apiKey={2}", HttpUtility.UrlEncode(longUrl), login, apikey);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
try
{
WebResponse response = request.GetResponse();
using (Stream responseStream = response.GetResponseStream())
{
StreamReader reader = new StreamReader(responseStream, Encoding.UTF8);
JavaScriptSerializer js = new JavaScriptSerializer();
dynamic jsonResponse = js.Deserialize<dynamic>(reader.ReadToEnd());
string s = jsonResponse["results"][longUrl]["shortUrl"];
return s;
}
}
catch (WebException ex)
{
WebResponse errorResponse = ex.Response;
using (Stream responseStream = errorResponse.GetResponseStream())
{
StreamReader reader = new StreamReader(responseStream, Encoding.GetEncoding("utf-8"));
String errorText = reader.ReadToEnd();
// log errorText
}
throw;
}
}
您可以从bit.ly获取登录名和apikey通过转到此链接
You can get your login and apikey from bit.ly by going to this link https://bitly.com/a/your_api_key
这篇关于Nuget包,用于缩短链接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!