Nuget包用于缩小链接

时间:2015-07-18 04:47:13

标签: .net bit.ly

我需要在C#中使用bitly来缩短我的链接。这有什么nuget包吗? 有人可以为我提供代码,以便我可以使用它。

5 个答案:

答案 0 :(得分:8)

查看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

答案 1 :(得分:7)

我遇到了Nuget包Bitly.Net的问题,所以我在上面实现了@ devfunkd的解决方案。但是我仍然在Azure see this related link上遇到了同样的问题,所以我不得不开发一个稍微不同的解决方案。

我的解决方案使用fixed OAuth Token进行身份验证,如bit.ly支持所示。它适用于Azure,并且具有不像旧版登录&#39; apiKey&#39;那样折旧的优点。如果这对某人有用,则代码based on @devfunkd 但更新为:

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

请注意,在代码中,字段_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;
    }
}

我希望能帮助别人。

答案 2 :(得分:1)

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

答案 3 :(得分:1)

    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

答案 4 :(得分:0)

这个使用bit.ly API v4:

{isLoggedIn == null
          ? <Stack.Navigator>
              <Stack.Screen
                name="Login"
                options={{headerShown: false}}
                component={Login}
              />
            </Stack.Navigator>
          : <Tab.Navigator>
              <Tab.Screen
                name="Home"
.......
........ rest code

必需的第三方软件包:Newtonsoft.Json,RestSharp。我还制作了一个GitHub项目,请参见此处:https://github.com/jabbalaci/CsUrlShortener