기본 HTTP 서버를 구축했으며 GET 요청에 대한 응답을 보내려고합니다. Gson을 JSON 파서로 설치했지만 JSON에서 응답을 인코딩하고 클라이언트에게 다시 보내는 방법을 모르겠습니다.Java에서 socket을 사용하여 JSON 응답을 보내는 방법
여기 내 코드입니다, 어떤 도움을 많이 주시면 감사하겠습니다. (실제 응답을위한 마지막 방법)
public class HttpServer extends Thread{
//Private variables
private Socket connectedClient = null;
private BufferedReader clientRequest = null;
private DataOutputStream responseToClient = null;
/**
* Public constructor
* @param client
*/
public HttpServer(Socket client){
connectedClient =client;
}
/**
* Code to execute on thread
*/
public void run(){
try {
//Log new client
System.out.println("The client " + connectedClient.getInetAddress() +
":" + connectedClient.getPort() + " is connected");
//Get the client request
clientRequest = new BufferedReader(new InputStreamReader(connectedClient.getInputStream()));
//Start response object
responseToClient = new DataOutputStream(connectedClient.getOutputStream());
//Process the request
processClientRequest();
//Close buffered writer
responseToClient.close();
} catch (Exception e) {
//Print error
e.printStackTrace();
}
}
/**
* Parses a client request and calls the approriate handler
* @throws Exception
*/
private void processClientRequest() throws Exception{
String requestString = clientRequest.readLine();
String header = requestString;
//Break up request
StringTokenizer tokenizer = new StringTokenizer(header);
//Different request parts
String httpMethod = tokenizer.nextToken();
String httpQueryString = tokenizer.nextToken();
//Print client request
StringBuffer responseBuffer = new StringBuffer();
while (clientRequest.ready()) {
responseBuffer.append(requestString + " ");
System.out.println(requestString);
requestString = clientRequest.readLine();
}
//ID GET request
if (requestString.equals("GET")) {
if (httpQueryString.equals("/")) {
sendResponse();
}
}
}
/**
* Sends reply back to client
* @throws Exception
*/
private void sendResponse() throws Exception{
HashMap<String, String> mapResponse = new HashMap<String, String>();
mapResponse.put("A", "Hands");
mapResponse.put("B", "Feet");
//Convert to JSON and send back to client
//?????????????????????????????
}
}
그리고 실제로 어떻게 다시 보내나요? responseToClient.writeBytes (json); ? –