I am trying make my own http server in Java.
The purpose of the application is to get RequestBody as json.
Parsing key and value to string seperately.
Running application with codes down below and when I use curl to test.
I get this error. Do you have any ideas?
curl http://127.0.0.1:33334 -d @test.json --header "Content-Type: application/json"
curl: (18) transfer closed with 32 bytes remaining to read
Main.java
package com.server.entry.http;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.server.functions.Init;
import com.server.models.ProgramArgument;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;
import org.apache.log4j.Logger;
import java.io.*;
import java.net.InetSocketAddress;
import java.util.*;
import java.util.concurrent.Executors;
public class Main {
static Logger logger = Logger.getLogger(Main.class);
public static void main(String[] args) throws Exception {
Init init = new Init();
ProgramArgument programArgument = new ProgramArgument();
init.sortArg(programArgument, args);
Properties p = init.readProperties(programArgument.getPropertiesPath());
init.configruProperties(p.getProperty("logPath"));
String hostName = p.getProperty("hostName");
int port = Integer.parseInt(p.getProperty("port"));
try {
HttpServer server = HttpServer.create(new InetSocketAddress(hostName,port), 10);
server.createContext("/", MyHandler.getInstance());
server.setExecutor(Executors.newCachedThreadPool());
server.start();
} catch (Exception e) {
logger.error("{}", e);
}
}
static class MyHandler implements HttpHandler {
private MyHandler() {}
public static MyHandler getInstance() {
return LazyHolder.INSTANCE;
}
private static class LazyHolder {
private static final MyHandler INSTANCE = new MyHandler();
}
@Override
public void handle(HttpExchange t) throws IOException {
String response = "This is the response";
t.sendResponseHeaders(200, response.length());
ObjectMapper mapper = new ObjectMapper();
Map<String, Object> jsonMap = mapper.readValue(t.getRequestBody(), Map.class);
Iterator<String> itr = jsonMap.keySet().iterator();
StringJoiner keyJoiner = new StringJoiner(",", "", "");
StringJoiner valueJoiner = new StringJoiner("','", "'", "'");
while(itr.hasNext())
{
String key = itr.next();
keyJoiner.add(key);
valueJoiner.add((String)jsonMap.get(key));
}
System.out.println(keyJoiner.toString());
System.out.println(keyJoiner.toString());
OutputStream os = t.getResponseBody();
os.write(response.getBytes());
os.close();
}
}
}
test.json
{
"name": "dddddddddd",
"email": "[email protected]",
"age": 25
}
I want to get result like this.
key : name,email,age , value : 'dddddddddd','[email protected]','25'
Thank you guys.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…