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.
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;
}
}
You can get your login and apikey from bit.ly by going to this link https://bitly.com/a/your_api_key
I had problems with the Nuget package Bitly.Net so I implemented @devfunkd's solution above. However I still had the same problems on Azure see this related link so I had to develop a slightly different solution.
My solution uses a fixed OAuth Token for authentication, as suggested by bit.ly support. It worked on Azure and has the advantage that it is not depreciated like the older 'login'/'apiKey'. In case this is useful to someone here is the code, based on @devfunkd but updated to:
- Use the fixed OAuth token for validation.
- Use the bit.ly's V3 API, which has a nicer json format.
- It uses Json.NET json deserialiser, which I mainly use.
- I made it async as most of the rest of my system is async.
Note that in the code the field _bitlyToken
should contain a token created by going to this page. The _logger
variable holds some sort of logger so that errors are not lost.
public async Task<string> ShortenAsync(string longUrl)
{
//with thanks to @devfunkd - see https://stackoverflow.com/questions/31487902/nuget-package-for-bitly-to-shorten-the-links
var url = string.Format("https://api-ssl.bitly.com/v3/shorten?access_token={0}&longUrl={1}",
_bitlyToken, HttpUtility.UrlEncode(longUrl));
var request = (HttpWebRequest) WebRequest.Create(url);
try
{
var response = await request.GetResponseAsync();
using (var responseStream = response.GetResponseStream())
{
var reader = new StreamReader(responseStream, Encoding.UTF8);
var jsonResponse = JObject.Parse(await reader.ReadToEndAsync());
var statusCode = jsonResponse["status_code"].Value<int>();
if (statusCode == (int) HttpStatusCode.OK)
return jsonResponse["data"]["url"].Value<string>();
//else some sort of problem
_logger.ErrorFormat("Bitly request returned error code {0}, status text '{1}' on longUrl = {2}",
statusCode, jsonResponse["status_txt"].Value<string>(), longUrl);
//What to do if it goes wrong? I return the original long url
return longUrl;
}
}
catch (WebException ex)
{
var errorResponse = ex.Response;
using (var responseStream = errorResponse.GetResponseStream())
{
var reader = new StreamReader(responseStream, Encoding.GetEncoding("utf-8"));
var errorText = reader.ReadToEnd();
// log errorText
_logger.ErrorFormat("Bitly access threw an exception {0} on url {1}. Content = {2}", ex.Message, url, errorText);
}
//What to do if it goes wrong? I return the original long url
return longUrl;
}
}
I hope that helps someone.
来源:https://stackoverflow.com/questions/31487902/nuget-package-for-bitly-to-shorten-the-links