我需要在C#中使用Bitly缩短链接。是否有NuGet包可以实现这一点?是否有人能够提供相应的代码,以便我可以使用它。
我在使用Nuget包Bitly.Net时遇到了问题,因此我实施了@devfunkd上面的解决方案。然而,在Azure上仍然存在相同的问题,请参阅此相关链接,因此我不得不开发一个稍微不同的解决方案。
我的解决方案使用固定的OAuth Token进行身份验证,正如bit.ly支持所建议的那样。它在Azure上运行,并且具有它不像旧的'login'/'apiKey'那样被弃用的优点。如果这对某人有用,这里是代码,基于@devfunkd但更新为:
请注意,在代码中,字段_bitlyToken
应包含通过访问此页面创建的令牌。变量_logger
保存某种记录器,以便不会丢失错误。
public async Task<string> ShortenAsync(string longUrl)
{
//with thanks to @devfunkd - see https://dev59.com/Ao3da4cB1Zd3GeqPviXO
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;
}
}
我希望这能对某人有所帮助。
请查看https://www.nuget.org/packages/BitlyAPI/,或直接调用bit.ly api。该api非常易于使用和操作。
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;
}
}
你可以通过访问此链接https://bitly.com/a/your_api_key从bit.ly获取您的登录和apikey。
ApiKey
已经被弃用了。 - Kiquenet public static async Task<string> ShortenUrl(string url)
{
string _bitlyToken = "<my token>";
HttpClient client = new HttpClient();
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post,
"https://api-ssl.bitly.com/v4/shorten")
{
Content = new StringContent($"{{\"long_url\":\"{url}\"}}",
Encoding.UTF8,
"application/json")
};
try
{
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", _bitlyToken);
var response = await client.SendAsync(request).ConfigureAwait(false);
if (!response.IsSuccessStatusCode)
return string.Empty;
var responsestr = await response.Content.ReadAsStringAsync();
dynamic jsonResponse = JsonConvert.DeserializeObject<dynamic>(responsestr);
return jsonResponse["link"];
}
catch (Exception ex)
{
return string.Empty;
}
}
这个可以在V4上运行
这个使用的是 bit.ly API v4:
using System.Collections.Generic;
using RestSharp;
using Newtonsoft.Json.Linq;
private static string API_KEY = Environment.GetEnvironmentVariable("BITLY_ACCESS_TOKEN");
private static string API_URL = "https://api-ssl.bit.ly/v4";
private static string Shorten(string longUrl)
{
var client = new RestClient(API_URL);
var request = new RestRequest("shorten");
request.AddHeader("Authorization", $"Bearer {API_KEY}");
var param = new Dictionary<string, string> {
{ "long_url", longUrl }
};
request.AddJsonBody(param);
var response = client.Post(request);
string content = response.Content;
// WriteLine(content);
JObject d = JObject.Parse(content);
var result = (string)d["id"];
return result;
}
需要的第三方包:Newtonsoft.Json,RestSharp。我还在GitHub上创建了一个项目,请参见此处:https://github.com/jabbalaci/CsUrlShortener。
这个例子只使用 Microsoft .net 原生代码。 您不需要任何其他第三方包,如 Newtonsoft.Json 或 RestSharp:
using System.Net.Http.Headers;
using System.Text;
using System.Text.Json;
using Bitly.Core.Requests;
using Bitly.Core.Responses;
namespace Bitly.Core
{
public class BitlyClient: IDisposable
{
private const string ApiUrl = "https://api-ssl.bitly.com/v4/shorten";
readonly string _token;
readonly HttpClient _client;
public BitlyClient(string token)
{
_token = token;
_client = new HttpClient();
}
public async Task<BitlyBaseResponse> ShortenAsync(string urlToShorten)
{
var jsonString = JsonSerializer.Serialize(new BitlyRequest{ LongUrl = urlToShorten });
var request = new HttpRequestMessage(HttpMethod.Post, ApiUrl)
{
Content = new StringContent(
jsonString,
Encoding.UTF8,
"application/json"
)
};
try
{
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", _token);
var response = await _client.SendAsync(request).ConfigureAwait(false);
if (!response.IsSuccessStatusCode)
return new BitlyGeneralErrorResponse(response.StatusCode.ToString());
var stringResponse = await response.Content.ReadAsStringAsync();
if (stringResponse.Contains("errors"))
{
var jsonErrorResponse = JsonSerializer.Deserialize<BitlyErrorResponse>(stringResponse);
return jsonErrorResponse;
}
var jsonResponse = JsonSerializer.Deserialize<BitlySuccessResponse>(stringResponse);
return jsonResponse;
}
catch (Exception ex)
{
return new BitlyGeneralErrorResponse(ex.Message);
}
}
public void Dispose()
{
_client?.Dispose();
}
}
}
请求模型:
public class BitlyRequest
{
[JsonPropertyName("long_url")]
public string LongUrl { get; set; }
}
public abstract class BitlyBaseResponse
{
public abstract bool Success { get; }
public abstract string Message { get; }
}
public class BitlyErrorResponse : BitlyBaseResponse
{
public string message { get; set; }
public string resource { get; set; }
public string description { get; set; }
public BitlyResponseError[] errors { get; set; }
public override bool Success => false;
public override string Message => message;
}
public class BitlyResponseError
{
public string field { get; set; }
public string error_code { get; set; }
}
public class BitlyGeneralErrorResponse : BitlyBaseResponse
{
public BitlyGeneralErrorResponse(string message)
{
Message = message;
}
public override bool Success => false;
public override string Message { get; }
}
public class BitlySuccessResponse : BitlyBaseResponse
{
public string created_at { get; set; }
public string id { get; set; }
public string link { get; set; }
public object[] custom_bitlinks { get; set; }
public string long_url { get; set; }
public bool archived { get; set; }
public object[] tags { get; set; }
public object[] deeplinks { get; set; }
public BitlyResponseReferences references { get; set; }
public override bool Success => true;
public override string Message => link;
}
public class BitlyResponseReferences
{
public string group { get; set; }
}
你可以像这样使用它:
var token = "<your_token>";
var client = new BitlyClient(token);
var url = "https://totpe.ro";
var response = await client.ShortenAsync(url);
你可以在这里找到所有的示例代码。