url에서 domain정보만 잘라낸다던가 프로토콜을 알아내고 싶다던가 query 내용을 분석하고 싶다던가 할때 주어진 url을 파싱하는 방법이다.
직접 만들어도 좋지만 스펙을 잘 모르면 라이브러리를 쓰는 것이 좋다.
java URL class를 사용하는데 방법은 아래와 같다.
출처 : http://download.oracle.com/javase/tutorial/networking/urls/urlInfo.html
코드
import java.net.*;
import java.io.*;
public class ParseURL {
public static void main(String[] args) throws Exception {
URL aURL = new URL("http://example.com:80/docs/books/tutorial"
+ "/index.html?name=networking#DOWNLOADING");
System.out.println("protocol = " + aURL.getProtocol());
System.out.println("authority = " + aURL.getAuthority());
System.out.println("host = " + aURL.getHost());
System.out.println("port = " + aURL.getPort());
System.out.println("path = " + aURL.getPath());
System.out.println("query = " + aURL.getQuery());
System.out.println("filename = " + aURL.getFile());
System.out.println("ref = " + aURL.getRef());
}
}
protocol = http authority = example.com:80 host = example.com port = 80 path = /docs/books/tutorial/index.html query = name=networking filename = /docs/books/tutorial/index.html?name=networking ref = DOWNLOADING/**
또, URI class에서는 아래와 같은 것도 제공한다. URI의 raw path를 알아내는 것
출처 : http://discuss.itacumens.com/index.php?topic=45734.0
코드
* @Program that Returns the raw path component of this URI.
* GetRawPath.java
* Author:-RoseIndia Team
* Date:-24-jun-2008
*/
import java.net.*;
public class GetRawPath {
public static void main(String[] args) throws Exception {
String scheme = "http";
String userInfo = "girish";
String host = "tewari.com";
int port = 8080;
String path = "/mail/";
String query = "open";
String fragment = "inbox";
URI uri = new URI(scheme, userInfo, host, port, path, query, fragment);
System.out.println("Given uri is: " + uri);
//Returns the raw path component of this URI.
System.out.println("Given raw path is: " + uri.getRawPath());
}
}
Given uri is: http://girish@tewari.com:8080/mail/?open#inbox
결과
Given raw path is: /mail/
'Crawling' 카테고리의 다른 글
크롤링에서 문서의 최신성 (freshness) (0) | 2011.09.06 |
---|---|
Url redirection (0) | 2011.08.12 |
url에 program으로 접근되지 않을 때 (0) | 2011.07.05 |
수집시에 HTTP 헤더의 if modified since (0) | 2011.06.24 |
url normalize (url 정규화) (0) | 2011.03.29 |