Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
4.8k views
in Technique[技术] by (71.8m points)

multithreading - How to set Java HTTP Server context handler threaded safe?

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Where are you call your curl command? If it's bash terminal it must run from a folder with your @test.json or you should change your path to file. I reproduce your trouble when I call curl with the parameter -d @test.json and bash terminal running from a different directory. This response happens because your inputStream is empty. When the path and file directory are correct I have a positive response.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...