在ASP.NET 2.0中使用Bit.ly API

问题描述 投票:5回答:4

嘿,我想知道是否有人可以指出如何在ASP.NET 2.0中使用Bit.ly API的示例

asp.net .net-2.0 bit.ly
4个回答
5
投票

我已经从VB中找到的答案进行了非常快速的转换。

我还没有测试这个(抱歉),但是在此期间它可能会有所帮助,我将其整理为对C#样式更友好。

public static string BitlyIt(string user, string apiKey, string strLongUrl)
{
   StringBuilder uri = new StringBuilder("http://api.bit.ly/shorten?");

   uri.Append("version=2.0.1");

   uri.Append("&format=xml");
   uri.Append("&longUrl=");
   uri.Append(HttpUtility.UrlEncode(strLongUrl));
   uri.Append("&login=");
   uri.Append(HttpUtility.UrlEncode(user));
   uri.Append("&apiKey=");
   uri.Append(HttpUtility.UrlEncode(apiKey));

   HttpWebRequest request = WebRequest.Create(uri.ToString()) as HttpWebRequest;
   request.Method = "GET";
   request.ContentType = "application/x-www-form-urlencoded";
   request.ServicePoint.Expect100Continue = false;
   request.ContentLength = 0;
   WebResponse objResponse = request.GetResponse();
   XmlDocument objXML = new XmlDocument();
   objXML.Load(objResponse.GetResponseStream());

   XmlNode nShortUrl = objXML.SelectSingleNode("//shortUrl");

   return nShortUrl.InnerText;
}

原始代码取自此处-http://www.dougv.com/blog/2009/07/02/shortening-urls-with-the-bit-ly-api-via-asp-net/


0
投票

我从蒂姆那里找到了答案,这很可靠。我需要一个vb.net版本,因此将其从C#转换回-我认为这可能会对某人有所帮助。似乎bit.ly链接已更改;不知道该版本是否不再需要;添加了一些错误处理,以防您输入错误的网址。

Public Shared Function BitlyIt(ByVal strLongUrl As String) As String

    Dim uri As New StringBuilder("http://api.bitly.com/v3/shorten?")

    'uri.Append("version=2.0.1") 'doesnt appear to be required

    uri.Append("&format=xml")
    uri.Append("&longUrl=")
    uri.Append(HttpUtility.UrlEncode(strLongUrl))
    uri.Append("&login=")
    uri.Append(HttpUtility.UrlEncode(user))
    uri.Append("&apiKey=")
    uri.Append(HttpUtility.UrlEncode(apiKey))

    Dim request As HttpWebRequest = TryCast(WebRequest.Create(uri.ToString()), HttpWebRequest)
    request.Method = "GET"
    request.ContentType = "application/x-www-form-urlencoded"
    request.ServicePoint.Expect100Continue = False
    request.ContentLength = 0

    Dim objResponse As WebResponse = request.GetResponse()

    Dim myXML As New StreamReader(objResponse.GetResponseStream())
    Dim xr = XmlReader.Create(myXML)
    Dim xdoc = XDocument.Load(xr)

    If xdoc.Descendants("status_txt").Value = "OK" Then

        Return xdoc.Descendants("url").Value

    Else

        Return "Error " & "ReturnValue: " & xdoc.Descendants("status_txt").Value

    End If

End Function

0
投票

BitlyIn的版本短一些

    public static string BitlyEncrypt2(string user, string apiKey, string pUrl)
    {
        string uri = "http://api.bit.ly/shorten?version=2.0.1&format=txt" +
            "&longUrl=" + HttpUtility.UrlEncode(pUrl) +
            "&login=" + HttpUtility.UrlEncode(user) +
            "&apiKey=" + HttpUtility.UrlEncode(apiKey);

        HttpWebRequest request = WebRequest.Create(uri) as HttpWebRequest;
        request.Method = "GET";
        request.ContentType = "application/x-www-form-urlencoded";
        request.ServicePoint.Expect100Continue = false;
        request.ContentLength = 0;

        return (new StreamReader(request.GetResponse().GetResponseStream()).ReadToEnd());
    }

0
投票
******* Migrating from v3 to v4 of the Bitly API - Bitly V4 code for ASP.NET Applications *******


public string Shorten(string groupId, string token, string longUrl)
{
//string post = "{\"group_guid\": \"" + groupId + "\", \"long_url\": \"" + longUrl + "\"}";
string post = "{ \"long_url\": \"" + longUrl + "\"}";// If you've a free account.
string shortUrl = "";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://api-ssl.bitly.com/v4/shorten");


try
{
ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072;

request.ServicePoint.Expect100Continue = false;
request.Method = "POST";
request.ContentLength = post.Length;
request.ContentType = "application/json";
request.Headers.Add("Cache-Control", "no-cache");
request.Host = "api-ssl.bitly.com";
request.Headers.Add("Authorization", "Bearer " + token);

using (Stream requestStream = request.GetRequestStream())
{
byte[] postBuffer = Encoding.ASCII.GetBytes(post);
requestStream.Write(postBuffer, 0, postBuffer.Length);
}

using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
using (Stream responseStream = response.GetResponseStream())
{
using (StreamReader responseReader = new StreamReader(responseStream))
{
string json = responseReader.ReadToEnd();
shortUrl = Regex.Match(json, @"""link"": ?""(?[^,;]+)""").Groups["link"].Value;

//return Regex.Match(json, @"{""short_url"":""([^""]*)""[,}]").Groups[1].Value;
}
}
}
}
catch (Exception ex)
{
LogManager.WriteLog(ex.Message);
}

if (shortUrl.Length > 0) // this check is if your bit.ly rate exceeded
return shortUrl;
else
return longUrl;
}
© www.soinside.com 2019 - 2024. All rights reserved.