JAVA_네트워크 (Network)

JW__1.7·2022년 8월 15일
0

JAVA 공부일지

목록 보기
26/30

URL

  • Uniform Resource Locator
  • 정형화된 자원의 경로
  • 웹 주소를 의미
  • 구성
import java.net.MalformedURLException;
import java.net.URL;

public class Main {

	public static void m1() {
    
    	try {
			// URL 처리를 위한 URL 클래스
			String apiURL = "https://search.naver.com/search.naver?query=날씨";
			URL url = new URL(apiURL);
			
			// URL 확인
			System.out.println("프로토콜 : " + url.getProtocol());
			System.out.println("호스트 : " + url.getHost());
			System.out.println("파라미터 : " + url.getQuery());
			
		} catch (MalformedURLException e) {
			System.out.println("API 주소 오류");
		}
	}
}
```java
프로토콜 : https
호스트 : search.naver.com
파라미터 : query=날씨

JAVA로 응답코드 출력하기

HttpURLConnection 클래스

  • 웹 접속을 담당하는 클래스
  • URL 클래스와 함께 사용
  • URLConnection 클래스의 자식 클래스
  • URLConnection 클래스의 openConnection() 메소드를 호출해서 HttpURLConnection 클래스 타입으로 저장

HTTP 응답 상태 코드

HTTP 응답 상태 코드는 특정 HTTP 요청이 성공적으로 완료되었는지 여부를 나타낸다.

  • 1xx : 정보응답
  • 2xx : 성공적인 응답
    • 요청 받은 프로세스를 계속 진행한다.
  • 3xx : 리디렉션 메시지
    • 리디렉션은 방문자에게 초기에 요청한 URL이 아닌 다른 URL을 제공하는 행위이다.
  • 4xx : 클라이언트 오류 응답
    • 요청 문법이 오류거나 요청을 처리할 수 없다.
  • 5xx : 서버 오류 응답
    • 서버가 명백하게 유효한 요청에 대한 충족을 실패했다.
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class Main {

	public static void m2() {
		
		try {
			// 접속하기
			String apiURL = "https://www.naver.com";
			URL url = new URL(apiURL);
			// 자식커넥션			// URL커넥션(부모)
			HttpURLConnection con = (HttpURLConnection)url.openConnection();
			
			// HTTP 응답 코드
			// 1. 200 : 정상
			// 2. 40X : 요청이 잘못됨 (사용자 잘못)
			// 3. 50X : 서버 오류
            
			// 접속 확인
			System.out.println("응답 코드 : " + con.getResponseCode());
			System.out.println("정상 : " + HttpURLConnection.HTTP_OK);
			System.out.println("Not Found : " + HttpURLConnection.HTTP_NOT_FOUND);
			System.out.println("Internal Error : " + HttpURLConnection.HTTP_INTERNAL_ERROR);
			
			System.out.println("컨텐트 타입 : " + con.getContentType());
			System.out.println("요청 방식 : " + con.getRequestMethod());
            
			// 접속 끊기
			con.disconnect();	// 접속 해제 (생략 가능)
			
		} catch (MalformedURLException e) {		// URL 클래스
			System.out.println("API 주소 오류");
		} catch (IOException e) {				// HttpURLConnection 클래스
			System.out.println("API 접속 오류");
		}
	}
}
응답 코드 : 200
정상 : 200
Not Found : 404
Internal Error : 500
컨텐트 타입 : text/html; charset=UTF-8
요청 방식 : GET

기존에 있는 웹페이지 읽어와서 출력하기

connection은 스트림을 만들기 위한 도구이다.
naver 메인페이지의 정보를 자바로 html 파일을 만들어 파일을 저장한다.

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class Main {

	public static void m3() {
		
		// HttpURLConnection과 스트림
		try {
			String apiURL = "https://www.naver.com";
			URL url = new URL(apiURL);
			HttpURLConnection con = (HttpURLConnection)url.openConnection();
			
			// 바이트 입력 스트림
			InputStream in = con.getInputStream();
					
			// 문자 입력 스트림으로 변환
			InputStreamReader reader = new InputStreamReader(in);
			
			// 모두 읽어서 StringBuilder에 저장
			StringBuilder sb = new StringBuilder();
			char[] cbuf = new char[100];	// 100 글자씩 처리
			int readCnt = 0;	// 실제로 읽은 글자 수
			
			while((readCnt = reader.read(cbuf)) != -1) {
				sb.append(cbuf, 0, readCnt);
			}
			// StringBuilder의 모든 내욜을 C:\\storage\\naver.com 로 내보내기
			File file = new File("C:\\storage", "naver.html");
			FileWriter fw = new FileWriter(file);
			
			fw.write(sb.toString());
			
			fw.close();
			reader.close();
			con.disconnect();
			
		} catch (MalformedURLException e) {
			System.out.println("API 주소 오류");
		} catch (IOException e) {
			System.out.println("API 접속 및 연결 오류");
		}
	}
}
// server → client = in Stream (바이트 기반 스트립)
// client → server = out Stream (바이트 기반 스트림)

인코딩(Incoding) / 디코딩(Decoding)

  • 인코딩 Incoding : UTF-8 방식으로 암호화
    • 원본 데이터를 암호화해서 알지 못하게 한다.
  • 디코딩 Decoding : UTF-8 방식으로 복호화
    • 암호화된 데이터를 원본 데이터로 다시 되돌리는 것이다.
  • 원본데이터 → 인코딩 → 전송 → 디코딩 → 원본데이터
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

public class Main {

	public static void m4() {
    
		try {
			// 원본 데이터
			String str1 = "한글 english 12345 !@#$+";
			
			// 인코딩
			String encode = URLEncoder.encode(str1, "UTF-8");
			System.out.println(encode);
			
			// 디코딩
			String decode = URLDecoder.decode(encode, StandardCharsets.UTF_8);
			System.out.println(decode);
			
			} catch (UnsupportedEncodingException e) {	// 인코딩 예외는 있지만, 디코딩 예외는 없다.
				e.printStackTrace();
			}
		
	}
}    
  • 공백을 인코딩하면 +로 변경
  • 원래 +2B로 변경

0개의 댓글