.NET 응용 프로그램에서 tinyurl.com 사용… 가능합니까?
문제
tinyurl.com URL을 만들기위한 다음 코드를 찾았습니다.
http://tinyurl.com/api-create.php?url=http://myurl.com
이것은 자동으로 작은 URL을 생성합니다. ASP.NET에서 코드, 특히 C#을 사용 하여이 작업을 수행하는 방법이 있습니까?
해결책
오류 검사 등을 추가해야 할 것입니다. 그러나 이것은 아마도 가장 쉬운 방법 일 것입니다.
System.Uri address = new System.Uri("http://tinyurl.com/api-create.php?url=" + YOUR ADDRESS GOES HERE);
System.Net.WebClient client = new System.Net.WebClient();
string tinyUrl = client.DownloadString(address);
Console.WriteLine(tinyUrl);
다른 팁
좀 더 연구를 한 후 ... 다음 코드를 우연히 발견했습니다.
public static string MakeTinyUrl(string url)
{
try
{
if (url.Length <= 30)
{
return url;
}
if (!url.ToLower().StartsWith("http") && !Url.ToLower().StartsWith("ftp"))
{
url = "http://" + url;
}
var request = WebRequest.Create("http://tinyurl.com/api-create.php?url=" + url);
var res = request.GetResponse();
string text;
using (var reader = new StreamReader(res.GetResponseStream()))
{
text = reader.ReadToEnd();
}
return text;
}
catch (Exception)
{
return url;
}
}
트릭을 할 수있는 것 같습니다.
본격적인 앱을 수행하는 경우 TinyUrl의 URL/API 체계에 매우 특정한 종속성으로 배선하고 있음을 명심하십시오. 어쩌면 그들은 URL이 바뀌지 않는 것에 대해 보장 할 수 있지만 체크 아웃 할 가치가 있습니다.
코드에서 해당 URL을 호출 한 다음 서버에서 출력을 다시 읽고 처리해야합니다.
살펴보십시오 System.net.webclient 수업, 다운로드 스트링 (또는 더 나은 : DownloadStringAsync) 당신이 원하는 것 같습니다.
에 따르면 이것 기사, 당신은 다음과 같이 구현할 수 있습니다.
public class TinyUrlController : ControllerBase
{
Dictionary dicShortLohgUrls = new Dictionary();
private readonly IMemoryCache memoryCache;
public TinyUrlController(IMemoryCache memoryCache)
{
this.memoryCache = memoryCache;
}
[HttpGet("short/{url}")]
public string GetShortUrl(string url)
{
using (MD5 md5Hash = MD5.Create())
{
string shortUrl = UrlHelper.GetMd5Hash(md5Hash, url);
shortUrl = shortUrl.Replace('/', '-').Replace('+', '_').Substring(0, 6);
Console.WriteLine("The MD5 hash of " + url + " is: " + shortUrl + ".");
var cacheEntryOptions = new MemoryCacheEntryOptions().SetSlidingExpiration(TimeSpan.FromSeconds(604800));
memoryCache.Set(shortUrl, url, cacheEntryOptions);
return shortUrl;
}
}
[HttpGet("long/{url}")]
public string GetLongUrl(string url)
{
if (memoryCache.TryGetValue(url, out string longUrl))
{
return longUrl;
}
return url;
}
}
여기에서 내 버전의 구현 :
static void Main()
{
var tinyUrl = MakeTinyUrl("https://stackoverflow.com/questions/366115/using-tinyurl-com-in-a-net-application-possible");
Console.WriteLine(tinyUrl);
Console.ReadLine();
}
public static string MakeTinyUrl(string url)
{
string tinyUrl = url;
string api = " the api's url goes here ";
try
{
var request = WebRequest.Create(api + url);
var res = request.GetResponse();
using (var reader = new StreamReader(res.GetResponseStream()))
{
tinyUrl = reader.ReadToEnd();
}
}
catch (Exception exp)
{
Console.WriteLine(exp);
}
return tinyUrl;
}
제휴하지 않습니다 StackOverflow