'Url'에 해당되는 글 2건
- 2008/03/13 URL 상대 경로, 절대 경로 변환 클래스 (C#)
- 2007/07/30 Resolve Relative URLS - URL 상대경로의 처리
Url Resolver클래스는 아래와 같은 기능들을 가지고 있습니다.
상대경로를 절대경로로 변환
상위 경로로 이동
Base URL 구하기
상대경로를 절대경로로 변환하는 기능에 북마크, 쿼리는 고려하지 않았으며, 일반적인 경우에 모두 정상적으로 동작합니다.
참고자료:
URL Relative Syntax and Base URLs - http://www.tcpipguide.com/free/t_URLRelativeSyntaxandBaseURLs-3.htm
URL 상대경로의 처리 - http://ljh131.tistory.com/6
public class UrlResolver
{
public static string GetBaseUrl(string url)
{
string baseUrl = url.Substring(0, url.LastIndexOf('/') + 1);
return baseUrl;
}
// return false if base url is root reached
public static bool GoUpOnePath(string baseUrl, out string newBaseUrl)
{
// 루트인지 체크 ('/' 개수가 3개이하면 중단)
int searchIndex = 0;
int count = 0;
int currentIndex = 0;
while (true)
{
currentIndex = baseUrl.IndexOf('/', searchIndex);
if (currentIndex != -1)
count++;
else
break;
searchIndex = currentIndex + 1;
}
if (count <= 3)
{
newBaseUrl = baseUrl;
return false;
}
// go up one
int secondOfLastSlashIndex = baseUrl.LastIndexOf('/', baseUrl.Length - 2);
newBaseUrl = baseUrl.Substring(0, secondOfLastSlashIndex + 1);
return true;
}
/*
* based on http://www.tcpipguide.com/free/t_URLRelativeSyntaxandBaseURLs-3.htm
* this function NOT include bookmark, query and new scheme url
*/
public static string GetAbsoluteUrl(string baseUrl, string relativeUrl)
{
// baseurl의 마지막은 반드시 /임
Debug.Assert(baseUrl.LastIndexOf('/') == baseUrl.Length - 1);
string[] relativePaths = { "//", "/", "./", "../", ".." };
bool resolveRelativePath = false;
do
{
resolveRelativePath = false;
foreach (string relativePath in relativePaths)
{
if (relativeUrl.IndexOf(relativePath) == 0)
{
resolveRelativePath = true;
switch (relativePath)
{
case "//": // 호스트 네임 지정
baseUrl = "http://";
break;
case "/": // 루트 지정
while (GoUpOnePath(baseUrl, out baseUrl))
;
break;
case "./": // 현재 디렉토리. 무시
break;
case "../": // 한단계 아래 디렉토리로 감. (더 이상 갈 수 없을때는 진행하지 않음.)
GoUpOnePath(baseUrl, out baseUrl);
break;
case "..": // 한단계 아래 디렉토리로 감. (../와 같음)
GoUpOnePath(baseUrl, out baseUrl);
break;
}
// remove relative path from url
relativeUrl = relativeUrl.Substring(relativePath.Length);
// reset loop
break;
}
}
} while (resolveRelativePath);
return baseUrl + relativeUrl;
}
}
'Programming > .NET' 카테고리의 다른 글
| URL 상대 경로, 절대 경로 변환 클래스 (C#) (0) | 2008/03/13 |
|---|---|
| C#으로 익스플로러 툴바 및 BHO만들기 (10) | 2007/11/07 |
| C#에서 unmanaged 함수 호출하기. (0) | 2007/08/31 |
| .NET 2.0 C#의 Configuration Manager (0) | 2007/08/30 |
| C# on multicore processor (or multi processor) - 멀티 프로세싱을 위한 C# (0) | 2007/07/30 |
HTTP를 이용한 프로그램을 만들때 가장 골치아프지만 중요한 것 중 하나는 상대경로의 처리이다.
상대경로는 파일시스템의 경우와 비슷하다. 예를 들어 현재 디렉토리가 c:\test이고, text.txt라는 상대경로가 주어졌을 때, 이를 절대경로로 표현하면 c:\test\text.txt이다. 반면 상대경로가 ../text.txt는 c:\text.txt를 가리킨다.
URL의 경우엔 파일경로의 이 개념을 단순히 URL 나타낸 정도 밖에 없다.http://WebReference.com/html/라는 Base URL이 있고, 이에 대한 Relative URL이 about.html라면 Absolute URL은 http://WebReference.com/html/about.html가 된다.
참고로 Base URL은 다음과 같이 계산한다.
User agents must calculate the base URI according to the following precedences (highest priority to lowest):
1. The base URI is set by the BASE element.
2. The base URI is given by meta data discovered during a protocol interaction, such as an HTTP header (see [RFC2616]).
3. By default, the base URI is that of the current document. Not all HTML documents have a base URI (e.g., a valid HTML document may appear in an email and may not be designated by a URI). Such HTML documents are considered erroneous if they contain relative URIs and rely on a default base URI.
1번과 2번이 우선순위가 높긴하지만 대부분은(귀찮으면) 3번으로 처리해도 된다.
파일 시스템의 경우와 같이 상대경로는 현재 URL내의 주소만 가르킬 수 있는것이 아니다. 상대경로의 앞에 디렉토리를 이동하는 특수한 문자를 붙여서 Base URL을 이동할 수 있는데 이는 /나 //, ../ 같이 지정된 형식이다.
이것을 해결하는 과정이 바로 상대경로 처리이다.
파이썬에서는 아주 고맙게도 라이브러리에서 지원해준다.
>>> import urlparse
>>> urlparse.urljoin('http://www.egloos.com/egloo/insert.php?eid=b0003850', '../test.html')
'http://www.egloos.com/test.html'
혹시 다른 언어에서 이 기능이 필요한데 라이브러리를 찾지 못한 경우엔 아래 두 링크를 보고 직접 만들면 된다.
http://www.webreference.com/html/tutorial2/3.html
http://www.tcpipguide.com/free/t_URLRelativeSyntaxandBaseURLs-3.htm
첫번째 링크의 예제는 단순해서 상대경로 '//www.internet.com/'가 ../와 비슷하게 보이지만 두번째 링크를 보면 알 수 있듯이, 이것은 호스트 네임을 바꾸는 것이므로 혼동하지 말자.
상대경로는 파일시스템의 경우와 비슷하다. 예를 들어 현재 디렉토리가 c:\test이고, text.txt라는 상대경로가 주어졌을 때, 이를 절대경로로 표현하면 c:\test\text.txt이다. 반면 상대경로가 ../text.txt는 c:\text.txt를 가리킨다.
URL의 경우엔 파일경로의 이 개념을 단순히 URL 나타낸 정도 밖에 없다.http://WebReference.com/html/라는 Base URL이 있고, 이에 대한 Relative URL이 about.html라면 Absolute URL은 http://WebReference.com/html/about.html가 된다.
참고로 Base URL은 다음과 같이 계산한다.
User agents must calculate the base URI according to the following precedences (highest priority to lowest):
1. The base URI is set by the BASE element.
2. The base URI is given by meta data discovered during a protocol interaction, such as an HTTP header (see [RFC2616]).
3. By default, the base URI is that of the current document. Not all HTML documents have a base URI (e.g., a valid HTML document may appear in an email and may not be designated by a URI). Such HTML documents are considered erroneous if they contain relative URIs and rely on a default base URI.
1번과 2번이 우선순위가 높긴하지만 대부분은(귀찮으면) 3번으로 처리해도 된다.
파일 시스템의 경우와 같이 상대경로는 현재 URL내의 주소만 가르킬 수 있는것이 아니다. 상대경로의 앞에 디렉토리를 이동하는 특수한 문자를 붙여서 Base URL을 이동할 수 있는데 이는 /나 //, ../ 같이 지정된 형식이다.
이것을 해결하는 과정이 바로 상대경로 처리이다.
파이썬에서는 아주 고맙게도 라이브러리에서 지원해준다.
>>> import urlparse
>>> urlparse.urljoin('http://www.egloos.com/egloo/insert.php?eid=b0003850', '../test.html')
'http://www.egloos.com/test.html'
혹시 다른 언어에서 이 기능이 필요한데 라이브러리를 찾지 못한 경우엔 아래 두 링크를 보고 직접 만들면 된다.
http://www.webreference.com/html/tutorial2/3.html
http://www.tcpipguide.com/free/t_URLRelativeSyntaxandBaseURLs-3.htm
첫번째 링크의 예제는 단순해서 상대경로 '//www.internet.com/'가 ../와 비슷하게 보이지만 두번째 링크를 보면 알 수 있듯이, 이것은 호스트 네임을 바꾸는 것이므로 혼동하지 말자.
'Programming > Web' 카테고리의 다른 글
| XPath로 HTML문서 접근하는 방법. (0) | 2007/08/13 |
|---|---|
| 비주얼 스튜디오로 자바스크립트 디버깅 하기 (0) | 2007/08/06 |
| ASP.NET 유닛 테스트의 해부학 (0) | 2007/08/01 |
| Ajax - 에이젝스? 아약스? 아작스?? (4) | 2007/07/30 |
| Resolve Relative URLS - URL 상대경로의 처리 (0) | 2007/07/30 |



Prev
Rss Feed