반응형
java 언어를 사용해서 json 서버 만들겠습니다.
socket을 이용해서 8080 포트 사용하는 소켓서버를 만들고, HTTP POST로 요청이 들어오는걸 header 및 body 부분
데이터를 읽어서 출력 및 응답 보내는 java 코드를 만들었습니다.
chunked transfer encoding 사용하는 HTTP 데이터 읽을 수 있게 만들었습니다.
json 데이터 테스트 할 때 서버가 필요하시면 사용하시면 될 것 같습니다.
JSON 서버 코드
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
107
108
109
110
111
|
import com.google.gson.Gson;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
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("\n");
}
String request = requestBuilder.toString();
System.out.println("Received request:\n" + request);
// Read HTTP request body (chunked)
StringBuilder requestBodyBuilder = new StringBuilder();
while (true) {
String line1 = inputReader.readLine();
if (line1 == null || line1.isEmpty()) {
break; // End of chunked data
}
int chunkSize = Integer.parseInt(line1, 16); // Hex to decimal
if (chunkSize == 0) {
break; // Last chunk
}
char[] chunkData = new char[chunkSize];
inputReader.read(chunkData, 0, chunkSize);
inputReader.readLine(); // Read CRLF after chunk data
requestBodyBuilder.append(chunkData);
}
String requestBody = requestBodyBuilder.toString();
System.out.println("Received request body:\n" + requestBody);
// Prepare JSON response
String jsonResponse = createJsonResponse();
byte[] jsonResponseBytes = jsonResponse.getBytes();
int contentLength = jsonResponseBytes.length;
// Send HTTP response headers
String httpResponse = "HTTP/1.1 200 OK\r\n"
+ "Content-Length: " + contentLength + "\r\n"
+ "Content-Type: application/json\r\n"
+ "Connection: close\r\n\r\n";
outputStream.write(httpResponse.getBytes());
// Send JSON response
outputStream.write(jsonResponseBytes);
outputStream.flush();
System.out.println("Sent response: " + jsonResponse);
} finally {
socket.close();
}
}
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 테스트
결과
해당 코드 분석해서 Refactoring 진행 해 봐도 좋을 것 같고, HTTP get 방식으로 수정해 보면 좋을 것 같습니다.
반응형