2009-09-05 11 views
8

제 3 자 웹 사이트 B로 리다이렉트되는 URL A가 주어지면 내 애플리케이션에서 주어진 URL A에 대한 URL B를 찾아 DB에 삽입해야합니다. Windows 응용 프로그램 또는 웹 또는 어느 것이 더 빠르고 C#을 사용하여 더 쉽습니다! 감사합니다.리디렉션 URL을 알아내는 방법

P. DB에 코드를 삽입 할 필요가 없습니다. 당신이 그렇게 이전 URL을보고 Linq에 또는 다른 ADO.NET 방법을 사용하여 DB에 저장할 수있는이 같은 코드를 사용할 수 있습니다 내가 당신의 질문에서 이해하는 것과

+2

이 달려 간다 역사를 구축하는 클래스입니다. 서버 측? 고객 측 (JS)? C#에있는 http 래퍼를 사용하여 URL을 가져 와서 301s/302s를 따르십시오. 운이 좋으면 그 일을 할 수있는 도서관이있을 수도 있습니다. B가 C로 리디렉션되면 어떻게됩니까? B 또는 C를 저장 하시겠습니까? 리디렉션을 얼마나 멀리 할 것입니까? C가 B로 리디렉션되면 어떻게됩니까? 방문한 주소를 추적하거나 리디렉션 제한을 설정하여 무한 리디렉션 루프를 피하십시오 (Firefox/Chrome에서이 문제를 처리하는 방법이라고 생각합니다). –

+0

서버 측 예제가 좋을 것 같습니다 ... 이것은 데이터 (즉, 최종 URL)를 추출하는 도구 일 뿐이므로 공상적 일 필요는 없습니다 ... 어떤 식 으로든 완료 될 수 있습니다! "A"는 항상 "B"로 리디렉션되며 거기에서 더 이상 발생하는 리다이렉션은 확립 된 사실입니다. –

+0

클라이언트 사이드 코드도 아프지 않습니다 ... IE의 인스턴스가 포함 된 Win Form 응용 프로그램이 작업을 수행해야한다고 가정합니다 ... 확실하지 않습니다. –

답변

10

WebRequest 클래스는 사용자 개입없이 리디렉션 다음, 그래서 리디렉션 302분의 301 개 상태 코드를 사용하는 경우 리디렉션이 '당신을 자바 스크립트 또는 HTTP-EQUIV 메타 태그를 사용하여 생성하는 경우 그 다음은

WebRequest request = WebRequest.Create(destination); 
WebResponse response = request.GetResponse(); 
Console.WriteLine(response.ResponseUri); 

를 작동합니다 페이지를 파싱하고이를 분석해야합니다. 아마도 HTML 민첩성 팩이이를 수행하는 가장 좋은 방법 일 것입니다.

이 조금 더 걸릴하려면 다음과 같이 수동으로 주요 HTTP 리디렉션 상태 코드를 해결는 리디렉션이 작동하는 방법

/// <summary> 
/// Digs through HTTP redirects until a non-redirected URL is found. 
/// </summary> 
public class Digger 
{ 
    /// <summary> 
    /// Initializes a new instance of the <see cref="Digger"/> class. 
    /// </summary> 
    public Digger() : this(20) 
    {    
    } 

    /// <summary> 
    /// Initializes a new instance of the <see cref="Digger"/> class. 
    /// </summary> 
    /// <param name="maximumDepth">The maximum depth of redirects to parse.</param> 
    public Digger(int maximumDepth) 
    { 
     this.MaximumDepth = maximumDepth; 
    } 

    /// <summary> 
    /// Gets the maximum depth of redirects to parse. 
    /// </summary> 
    /// <value>The maximum depth of redirects to parse.</value> 
    public int MaximumDepth 
    { 
     get; 
     private set; 
    } 

    /// <summary> 
    /// Resolves any redirects at the specified URI. 
    /// </summary> 
    /// <param name="destination">The initial URI.</param> 
    /// <returns>The URI after resolving any HTTP redirects.</returns> 
    public Uri Resolve(Uri destination) 
    { 
     List<Uri> redirectHistory = new List<Uri>(); 
     return this.Resolve(destination, redirectHistory); 
    } 

    /// <summary> 
    /// Resolves any redirects at the specified URI. 
    /// </summary> 
    /// <param name="destination">The initial URI.</param> 
    /// <param name="redirectHistory">A collection of <see cref="Uri"/> objects representing the redirect history.</param> 
    /// <returns>The URI after resolving any HTTP redirects.</returns> 
    public Uri Resolve(Uri destination, ICollection<Uri> redirectHistory) 
    { 
     redirectHistory.Add(destination); 
     return this.Resolve(destination, this.MaximumDepth, redirectHistory); 
    } 

    /// <summary> 
    /// Resolves any redirects at the specified URI. 
    /// </summary> 
    /// <param name="destination">The initial URI.</param> 
    /// <param name="hopsLeft">The maximum number of redirects left to follow.</param> 
    /// <param name="redirectHistory">A collection of <see cref="Uri"/> objects representing the redirect history.</param> 
    /// <returns>The URI after resolving any HTTP redirects.</returns> 
    private Uri Resolve(Uri destination, int hopsLeft, ICollection<Uri> redirectHistory) 
    { 
     HttpWebRequest request = (HttpWebRequest)WebRequest.Create(destination); 
     request.AllowAutoRedirect = false; 
     request.Method = "HEAD"; 

     HttpWebResponse response = (HttpWebResponse)request.GetResponse(); 

     Uri resolvedUri; 

     if (response.StatusCode == HttpStatusCode.Redirect || 
      response.StatusCode == HttpStatusCode.Moved || 
      response.StatusCode == HttpStatusCode.MovedPermanently) 
     { 
      if (hopsLeft > 0) 
      { 
       Uri redirectUri = new Uri(response.GetResponseHeader("Location")); 
       if (redirectHistory.Contains(redirectUri)) 
       { 
        throw new Exception("Recursive redirection found"); 
       } 

       redirectHistory.Add(redirectUri); 
       resolvedUri = this.Resolve(redirectUri, hopsLeft - 1, redirectHistory); 
      } 
      else 
      { 
       throw new Exception("Maximum redirect depth reached"); 
      } 
     } 
     else 
     { 
      resolvedUri = response.ResponseUri; 
     } 

     return resolvedUri;    
    } 
} 
+0

감사합니다. 완벽하게 작동합니다! –

+0

위치 헤더에 상대 URI가 있으면 작동하지 않습니다. 나는 믿는다 :'Uri redirectUri; if (! Uri.TryCreate (location, UriKind.Absolute, out redirectUri)) {if (! Uri.TryCreate (response.ResponseUri, location, out redirectUri)) {throw new WebException ("잘못된 리디렉션"); }}'더 많은/대부분/(모든 경우 별이 정렬 된 경우)에서 작동하지만 아직 완전히 테스트하지는 않았습니다. –

+0

정말 대단한 대답입니다. – Ikaso

0
Uri MyUrl = Request.UrlReferrer; 
Response.Write("Referrer URL Port: " + Server.HtmlEncode(MyUrl.Port.ToString()) + "<br>"); 
Response.Write("Referrer URL Protocol: " + Server.HtmlEncode(MyUrl.Scheme) + "<br>"); 

.

LINQ를 사용하여 db에 레코드를 저장하는 방법을 알고 있다고 가정합니다. 하지 않으면 다음 링크를 따르십시오. LINQ to SQL - 5 Minute Overview

희망이 있습니다.

관련 문제