본문 바로가기

Java/Java 기초

Simple Java HttpServer and HttpURLConnection

HttpServer

import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;

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

public class HttpServerApplication {
    final static HttpHandler indexHandler = httpExchange -> {
        final String response = "This is index page...";
        httpExchange.sendResponseHeaders(200, response.length());

        final OutputStream os = httpExchange.getResponseBody();
        os.write(response.getBytes());
        os.close();
    };

    public static void main(String[] args) {
        try {
            final HttpServer server = HttpServer.create(new InetSocketAddress(8000), 0);
            server.createContext("/", indexHandler);
            server.setExecutor(null);
            server.start();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

 

HttpURLConnection

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

public class HttpURLConnectionApplication {
    public static void main(String[] args) {
        try {
            final URL url = new URL("http://localhost:8000");
            final HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");
            connection.setRequestProperty("User-Agent", "Mozilla/5.0");

            final BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));

            String inputLine;
            final StringBuilder builder = new StringBuilder();

            while ((inputLine = in.readLine()) != null) {
                builder.append(inputLine);
            }
            in.close();
            System.out.println("response code=" + connection.getResponseCode());
            System.out.println("response body=" + builder.toString());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

'Java > Java 기초' 카테고리의 다른 글

Java Custom Annotation  (0) 2020.05.13
ParallelStream의 결과를 List에 저장  (1) 2019.11.08
Java Reflection 사용하기 (7)  (0) 2019.02.18
Java Reflection 사용하기 (6)  (0) 2019.02.15
Java Reflection 사용하기 (5)  (0) 2019.02.15