자바에서 간단한 웹파싱 하는 방법
자신의 공인아이피를 보여줄 사이트인 http://ipip.kr 이다.
웹 구조가 가장 간단하게 잘 나와있어 파싱하기 쉽다.
------------코드
public static void main(String[] a){
String IP = null;
try{
//파싱 할 사이트를 URL로 선언한다.
URL u = new URL("http://ipip.kr");
InputStreamReader input = new InputStreamReader(u.openStream());
BufferedReader br = new BufferedReader(input);
String Line;
while((Line=br.readLine())!=null) System.out.println(Line);
} catch(Exception e){ e.printStackTrace(); }
}
--------------결과
<head>
<title>Your IP is (자신의아이피)</title>
</head>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=euc-kr">
<title>++ ipip.kr ++</title>
<meta name="generator" content="Namo WebEditor v5.0">
</head>
<body bgcolor="#BBFFFF" text="black" link="blue" vlink="purple" alink="red">
<br><br><br><br>
<table align="center" cellpadding="0" cellspacing="0">
(===========중략============)
</table>
<p align="center"><b><font color="#3399FF"><span style="font-size:10pt;">Your
IP is </span></font><font color="#0066FF"><span style="font-size:11pt;">(자신의아이피)</span></font></b></p>
<p align="center"><b><font color="#0066FF"><span style="font-size:11pt;"> </span></font></b></p>
<p align="center"><b><font color="red" face="맑은 고딕"><span style="font-size:11pt;"></span></font></b></p>
<br>
<font color="#0066FF"><br><center><span style='font-size:9pt'>[ ipip.kr은 트래픽 부하 없이 간단하게 자신의 IP를 보여주는 사이트입니다. ]<br><br><br>Copyright @ 2000~2013 HACKERSCHOOL All right reserved.
<br>
</body>
</html>
이런식의 결과가 나오게 되는데 (자신의아이피) 라고 써저있는 곳은 파싱했을 때 파싱한 컴퓨터의 공인아이피가 나오는 자리이다
간단하게 보기 위해서는 아래 복잡한 부분이 아닌 위의 <title> 부분의 아이피를 replace 로 추려내어
쉽게 아이피 값만 얻어 올 수 있다.
부가적으로
<title>Your IP is (자신의아이피)</title>
이 구문에서 자신의 아이피만 남기고 모두 지우는 방법은
replace를 사용해 자신의 아이피만 남기고 앞 뒤를 모두 빈칸으로 치환해버리면 간단하게 끝난다.
'Java > Java Note' 카테고리의 다른 글
자바 모래시계 알고리즘 (0) | 2017.04.02 |
---|---|
자바 java.util.ConcurrentModificationException (0) | 2017.04.02 |
이클립스 테마 변경하기 (0) | 2017.04.02 |
이클립스 기본인코딩 변경하기(UTF-8) (0) | 2017.04.01 |
자바 소켓통신하는법 (0) | 2017.04.01 |