본문 바로가기

좋아하는 것_매직IT/26.Java

HttpServer를 활용한 간단한 Mock 서버 구축하기

반응형

블로그 목적

HttpServer을 활용한 간단한 Mock 서버 구축에 대한 공부및 정리후 나만의 노하우와 지식을 공유한다.

블로그 요약

1. HttpServer 에 대해서 알아본다.
2.
HttpServer 을 통해서 Mock 서버를 구축해본다.

블로그 상세내용
HttpServer 란?

JAVA api 문서를 확인해보니 아래와 같이 설명하고 있습니다. (개인적으로 잘 정리해두시고요...)
This class implements a simple HTTP server. A HttpServer is bound to an IP address and port number and listens for incoming TCP connections from clients on this address. The sub-class HttpsServer implements a server which handles HTTPS requests.
(한마디로 단순한 HTTP 서버를 구현하기 위한 클래쓰!!)

주요 메소드를 확인해보니 아래와 같았다.

출처 : 오라클

한번 쭈우욱 읽어보시면 좋을것 같고요...
그중에 머릿속에 넣어둘 메소드는 아래와 같은데요..
(말그대로 소켓생성및 포트를 바인드하기위한 용도죠...)

그리고 위에서 확인하실 수 있는것과 같이, createContext 도 필요하니 머릿속에 넣어두셔야 합니다.

요청을 받아서 처리하려면..HttpContext 를 만들어야 하니깐요!!

그외에 HttpHandler 에 대해서도 공부해 보시면 좋을것 같네요..




HttpServer 을 통한 Mock 서버 구축 하기

위의 지식을 기반으로 간단한 예제 코드를 작성해보면요 아래와 같습니다.

import java.io.IOException;
import java.net.InetSocketAddress;

import com.sun.net.httpserver.HttpServer;

public class HttpServerTest {

	public static void main(String[] args) throws IOException {
		HttpServer server = HttpServer.create(new InetSocketAddress(8080), 0);
		server.createContext("/", he -> {
			String body = "hello test http server";
			he.sendResponseHeaders(200, body.length());
			he.getResponseBody().write(body.getBytes());
			he.getRequestBody().close();
		});
		server.start();
		System.out.println("server started at :8080");
	}

}

728x90
300x250