Programming/JAVA / / 2024. 3. 25. 20:15

[JAVA] JSON 서버 만들기(HTTP POST 요청 Content-Length)

반응형

java 언어를 사용해서 json 서버 만들겠습니다.
socket을 이용해서 8080 포트 사용하는 소켓서버를 만들고, HTTP POST로 요청이 들어오는걸 header 및 body 부분
데이터를 읽어서 출력 및 응답 보내는 java 코드를 만들었습니다.
Http header 에 Content-Length 사용하는 HTTP  데이터 읽을 수 있게 만들었습니다.
json 데이터 테스트 할 때 서버가 필요하시면 사용하시면 될 것 같습니다.

 

JSON server 코드

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
import com.google.gson.Gson;
 
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
 
public class JsonServer {
 
    public static void main(String[] args) {
        final int portNumber = 8080;
 
        try (ServerSocket serverSocket = new ServerSocket(portNumber)) {
            System.out.println("Server started. Listening on port " + portNumber);
 
            while (true) {
                Socket socket = serverSocket.accept();
                System.out.println("Client connected: " + socket);
 
                // Handle client request in a new thread
                new Thread(() -> {
                    try {
                        handleClient(socket);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }).start();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
 
    private static void handleClient(Socket socket) throws IOException {
        try (BufferedReader inputReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
             OutputStream outputStream = socket.getOutputStream()) {
 
            // Read HTTP request headers
            StringBuilder requestBuilder = new StringBuilder();
            String line;
            line = inputReader.readLine();
            if(line == null) {
                return;
            }
            while ((line = inputReader.readLine()) != null && !line.isEmpty()) {
                requestBuilder.append(line).append("\r\n");
            }
            String request = requestBuilder.toString();
            System.out.println("Received request:\n" + request);
 
            // Read HTTP request body if Content-Length is present
            String body = "";
            if (request.contains("Content-Length")) {
                int contentLength = getContentLength(request);
                char[] buffer = new char[contentLength];
                int bytesRead = inputReader.read(buffer, 0, contentLength);
                body = new String(buffer, 0, bytesRead);
            }
            System.out.println("body message : "+body);
 
            // Prepare JSON response
            String jsonResponse = createJsonResponse();
 
            // Send HTTP response
            String httpResponse = "HTTP/1.1 200 OK\r\n"
                    + "Content-Length: " + jsonResponse.getBytes().length + "\r\n"
                    + "Content-Type: application/json\r\n"
                    + "Connection: close\r\n\r\n";
            outputStream.write(httpResponse.getBytes());
            outputStream.write(jsonResponse.getBytes());
            outputStream.flush();
            System.out.println("Sent response: " + jsonResponse);
        } finally {
            socket.close();
        }
    }
 
    private static int getContentLength(String request) {
        String[] lines = request.split("\r\n");
        for (String line : lines) {
            if (line.startsWith("Content-Length:")) {
                return Integer.parseInt(line.split(":")[1].trim());
            }
        }
        return 0;
    }
 
    private static String createJsonResponse() {
        // This method would generate the data for the JSON response
        // For demonstration, let's create a simple JSON response string
        Gson gson = new Gson();
        return gson.toJson(new Response("Hello, client!"));
    }
 
    // Sample Response class
    static class Response {
        private final String message;
 
        public Response(String message) {
            this.message = message;
        }
 
        public String getMessage() {
            return message;
        }
    }
}
cs

 

POSTMAN 테스트

 

결과

 

반응형
  • 네이버 블로그 공유
  • 네이버 밴드 공유
  • 페이스북 공유
  • 카카오스토리 공유