개발자 미니민의 개발스터디

[JAVA] 자바 - InetAddress 클래스 / URL 클래스

by mini_min
[JAVA]
자바 - InetAddress 클래스 / URL 클래스

✔️ InetAddress 클래스

인터넷 상의 IP 주소를 객체 모델링한 클래스이다.

IP 주소와 관련된 여러 정보를 제공한다!

✨ Inet + 숫자 + Address : 인터넷 프로코톨 버전 (숫자) 주소를 나타낸다.

 

public static void main(String[] args) {
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		
		String host;
		
		try {
			System.out.println("호스트이름[www.naver.com] ? ");
			host = br.readLine();
			
			InetAddress ia = InetAddress.getByName(host);
			
			// 호스트이름
			String s = ia.getHostName();
			
			// 아이피 주소
			String ip = ia.getHostAddress();
			
			System.out.println("호스트 이름 : " + s);
			System.out.println("아이피 주소 : " + ip);
			
			
		} catch (Exception e) {
			// TODO: handle exception
		}

	}
💡 InetAddress ia = InetAddress.getByName(host);

💡 호스트 이름 따기 : getHostName();
💡 아이피 주소 따기 : getHostAddress();

 

 

✔️ URL 클래스

URL : 네트워크 상에서 자원이 어디 있는지 알려주기 위한 규약이다.

웹 사이트 주소 뿐만 아니라 컴퓨터 네트워크 상의 자원을 모두 나타낼 수 있다!

✨ URL 구성 : 프로토콜:// 호스트 :[포트번호]/[파일]#[세션]

 

 URL 클래스는 웹 상에 존재하는 자원에 접근하기 위해, 자원의 유일한 주소를 나타내기 위한 기능을 제공한다.

자원이란, 파일 또는 디렉토리, 데이터베이스, 서치 엔진에 대한 쿼리와 같은 객체가 해당될 수 있다.

 

📓 URL 클래스 주요 메소드

getFile() : 파일 부분을 얻음

getHost() : 호스트 부분을 얻음 .... 

 

public static void main(String[] args) {
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		String webUrl, s;
		
		BufferedReader wbr = null;
		
		try {
			
			System.out.println("웝주소[https://www.naver.com] ? ");
			webUrl = br.readLine();
			
			// URL : 웹상의 리소스에 대한 포인터를 나타냄
			URL url = new URL(webUrl);
			InputStream is = url.openStream();
			wbr = new BufferedReader(new InputStreamReader(is, "utf-8"));
			
			while((s = wbr.readLine()) != null) {
				System.out.println(s);
			}
			
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if(wbr != null) {
				try {
					wbr.close();
				} catch (Exception e2) {
				}
			}
		}

	}
💡 URL url = new URL(webUrl); : URL 을 가지고 객체 생성
💡 InputStream openStream() : URL 이 가리키고 있는 원격 객체에 대한 연결을 나타내는 URLConnection 객체를 얻는다! 

 

 

✔️ URLConnection 클래스

추상 클래스이다. 애플리케이션과 URL 간의 통신 링크를 위한 모든 클래스에 대한 상위 클래스이다.

해당 객체는, URL 을 이용하여 참조된 자원을 읽고 쓰는 작업을 할 수 있도록 해준다.

 

 

✔️ URLEncoder/Decode 클래스

Encode : HTML 형식을 인코딩하기 위한 유틸리티 클래스이다.

static 메소드를 제공한다. 

📓 static String encode (String s, String enc)

 

Decode : HTML 형식을 디코드하기 위한 유틸리티 클래스이다.

📓 static String decode (String s, String enc)

public static void main(String[] args) {
		String s1, s2;
		
		try {
			
			s1 = "자바 java123";
			
			// 문자열을 인터넷 상태에서 전송할 수 있도록 주소형식으로 변환
			// (application/x-www-form-urlencoded)
			s2 = URLEncoder.encode(s1, "utf-8");
			System.out.println("인코딩 결과 : " + s2);
			
			s1 = URLDecoder.decode(s1, "utf-8");
			System.out.println("디코딩 결과 : " + s1);
			
		} catch (Exception e) {
			e.printStackTrace();
		}

		
		
		
		
	}

 

 

 

 

 

블로그의 정보

개발자 미니민의 개발로그

mini_min

활동하기