.net Nuget包bitly缩短链接

qmelpv7a  于 2023-04-13  发布在  .NET
关注(0)|答案(6)|浏览(141)

我需要在C#中使用bitly缩短我的链接。有没有任何nuget包?有人可以提供我的代码,以便我可以使用它。

e0bqpujr

e0bqpujr1#

查看https://www.nuget.org/packages/BitlyAPI/或者自己调用bit.lyAPI。该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;
    }
}

您可以从www.example.com获取您的登录名和apikeybit.ly,访问此链接https://bitly.com/a/your_api_key

ulydmbyx

ulydmbyx2#

我在Nuget包Bitly.Net上遇到了问题,所以我实现了上面@devfunkd的解决方案。但是我在Azure see this related link上仍然遇到了同样的问题,所以我不得不开发一个稍微不同的解决方案。
我的解决方案使用fixed OAuth Token进行身份验证,正如bit.ly支持所建议的那样。它在Azure上工作,并且具有不像旧的'login'/'apiKey'那样贬值的优点。如果这对某人有用,这里是代码,基于@devfunkd,但更新为:

  • 使用固定的OAuth令牌进行验证。
  • 使用bit.ly的V3 API,它具有更好的json格式。
  • 它使用Json.NET json反序列化器,我主要使用它。
  • 我让它异步,因为我的系统的大部分其余部分是异步的。

请注意,在代码中,字段_bitlyToken应该包含通过转到this page创建的令牌。_logger变量保存某种类型的日志记录器,以便不会丢失错误。

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;
    }
}

我希望这对某人有帮助。

zpqajqem

zpqajqem3#

其他答案都很棒,但示例代码将不再工作https://www.nuget.org/packages/BitlyAPI/4.0.0已更新,因此您可以使用它或在github https://github.com/doublej42/BitlyAPI中查看它的代码

jaxagkaj

jaxagkaj4#

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的

sqserrrh

sqserrrh5#

下面的例子使用了bit.lyAPI 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

eiee3dmh

eiee3dmh6#

此示例仅使用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);

你可以找到所有的示例代码here

相关问题