JAVA/HIGH JAVA

[JAVA] 네트워킹 - InetAddress, URL, URLConnection

아잠만_ 2024. 5. 8. 12:21

InetAddress

InetAddress 클래스 
==> IP주소를 다루기 위한 클래스

  • getByName
  • getHostAddress
  • toString
  • getLocalHost
  • getAllByName
import java.net.InetAddress;
import java.net.UnknownHostException;

public class InetAddressTest {
	public static void main(String[] args) throws UnknownHostException {
		// InetAddress 클래스 ==> IP주소를 다루기 위한 클래스
		
		// www.naver.com의 IP정보 가져오기
		InetAddress ipTest = InetAddress.getByName("www.nate.com");
		
		System.out.println("hostName : "+ipTest.getHostName());	// hostName : www.nate.com
		System.out.println("hostAddress : "+ipTest.getHostAddress());	// hostAddress : 120.50.131.112
		System.out.println("toString : "+ipTest.toString());	// toString : www.nate.com/120.50.131.112
		System.out.println();
		
		// 자신의 컴퓨터의 IP정보 가져오기
		InetAddress localIp = InetAddress.getLocalHost();
		System.out.println("hostName : "+localIp.getHostName());	// hostName : DESKTOP-062MQF6
		System.out.println("hostAddress : "+localIp.getHostAddress());
		System.out.println();
		
		// IP주소가 여러개인 호스트의 정보 가져오기
		InetAddress[] ipArr = InetAddress.getAllByName("www.naver.com");
		for(InetAddress ip : ipArr) {
			System.out.println(ip.toString());
//			www.naver.com/223.130.200.236
//			www.naver.com/223.130.200.219
//			www.naver.com/223.130.192.248
//			www.naver.com/223.130.192.247
		}
	}
}

URL

URL클래스 ==> 인터넷에 존재하는 서버들의 자원에 접근할 수 있는 주소를 다루는 클래스

URL주소의 구조
프로토콜://호스트명(또는 IP주소):포트번호/경로명/파일명?쿼리스트링#참조
예시 : http://ddit.or.kr:80/test/index.html?ttt=333

import java.net.MalformedURLException;
import java.net.URL;
import java.nio.charset.MalformedInputException;

public class URLTest01 {
	public static void main(String[] args) throws MalformedURLException{
		// URL클래스 ==> 인터넷에 존재하는 서버들의 자원에 접근할 수 있는 주소를 다루는 클래스
		
		// URL주소의 구조
		//	프로토콜://호스트명(또는 IP주소):포트번호/경로명/파일명?쿼리스트링#참조
		// 	http://ddit.or.kr:80/test/index.html?ttt=333
		
		URL url = new URL("http","ddit.or.kr",80,"/test/index.html?ttt=123");
		
		System.out.println("Protocol : "+url.getProtocol());	// Protocol : http
		System.out.println("Host : "+url.getHost());	// Host : ddit.or.kr
		System.out.println("Port : "+url.getPort());	// Port : 80
		System.out.println("File : "+url.getFile());	// File : /test/index.html?ttt=123
		System.out.println("Path : "+url.getPath());	// Path : /test/index.html
		System.out.println("Query : "+url.getQuery());	// Query : ttt=123
		System.out.println();
		
		System.out.println(url.toExternalForm());	// http://ddit.or.kr:80/test/index.html?ttt=123
	}
}

URLConnection

URLConnection 

==> 애플리케이션과 URL간의 통신연결을 위한 클래스

url객체.openConnection() > URLConnection객체로 변환

 

해당 문서의 내용을 가져와 출력하기

방법 1

URLConnection 객체를 이용하는 방법
InputStream 스트림이름 = Connection객체.getInputStream();

inputStream -> inputsteamReader -> BufferedReader

 

방법 2

URL객체의 openStream() 메서드를 이용하는 방법

InputStream 스트림이름 = url객체.openStream();
inputStream -> inputsteamReader -> BufferedReader


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;
import java.util.Map;

public class URLTest02 {
	public static void main(String[] args) throws IOException {
		// URLConnection ==> 애플리케이션과 URL간의 통신연결을 위한 클래스
		
		// 특정 서버의 정보와 파일내용을 가져와 출력하는 예제
		URL url = new URL("http://www.naver.com/index.html");
		
		// URLConnection객체 구하기
		URLConnection conn = url.openConnection();
		
		// Header 정보 가져오기
		Map<String, List<String>> headerMap = conn.getHeaderFields();
		
		// headerMap의 key값과 value값 출력
		for(String key : headerMap.keySet()) {
			System.out.println(key + " : "+headerMap.get(key));
		}
//		null : [HTTP/1.1 302 Moved Temporarily]
//		server : [nfront]
//		transfer-encoding : [chunked]
//		vary : [Accept-Encoding,User-Agent]
//		referrer-policy : [unsafe-url]
//		location : [https://www.naver.com/index.html]
//		content-type : [text/html]
//		Date : [Wed, 08 May 2024 02:49:20 GMT]
		System.out.println();
		
		// 해당 문서의 내용을 가져와 출력하기 (index.html문서의 내용 가져오기)
		
		// 방법1) URLConnection 객체를 이용하는 방법
		
		// 파일을 읽어오기 위한 스트림 객체 생성
		InputStream is = conn.getInputStream();
		InputStreamReader isr = new InputStreamReader(is, "utf-8");
		BufferedReader br = new BufferedReader(isr);
		
		// 자료의 내용을 읽어와 출력하기
		String str = null;	// 읽어온 자료가 저장될 변수
		while( (str=br.readLine())!=null ) {
			System.out.println(str);
		}
		br.close(); // 스트림 닫기
		
		System.out.println();
		
		// 방법 2) URL객체의 openStream() 메서드를 이용하는 방법
		InputStream is2 = url.openStream();
		BufferedReader br2 = new BufferedReader(new InputStreamReader(is2));
		
		// 자료의 내용을 읽어와 출력하기
		String str2 = null;	// 읽어온 자료가 저장될 변수
		while( (str2=br2.readLine())!=null ) {
			System.out.println(str2);
		}
		br2.close(); // 스트림 닫기
		
	}
}