simple HTTP server in Java using only Java SE API

前端 未结 17 1709
无人共我
无人共我 2020-11-22 13:28

Is there a way to create a very basic HTTP server (supporting only GET/POST) in Java using just the Java SE API, without writing code to manually parse HTTP requests and man

相关标签:
17条回答
  • 2020-11-22 14:04

    Have a look at the "Jetty" web server Jetty. Superb piece of Open Source software that would seem to meet all your requirments.

    If you insist on rolling your own then have a look at the "httpMessage" class.

    0 讨论(0)
  • 2020-11-22 14:05

    Check out takes. Look at https://github.com/yegor256/takes for quick info

    0 讨论(0)
  • 2020-11-22 14:07

    Try this https://github.com/devashish234073/Java-Socket-Http-Server/blob/master/README.md

    This API has creates an HTTP server using sockets.

    1. It gets a request from the browser as text
    2. Parses it to retrieve URL info, method, attributes, etc.
    3. Creates dynamic response using the URL mapping defined
    4. Sends the response to the browser.

    For example the here's how the constructor in the Response.java class converts a raw response into an http response:

    public Response(String resp){
        Date date = new Date();
        String start = "HTTP/1.1 200 OK\r\n";
        String header = "Date: "+date.toString()+"\r\n";
        header+= "Content-Type: text/html\r\n";
        header+= "Content-length: "+resp.length()+"\r\n";
        header+="\r\n";
        this.resp=start+header+resp;
    }
    
    0 讨论(0)
  • 2020-11-22 14:10

    Since Java SE 6, there's a builtin HTTP server in Sun Oracle JRE. The com.sun.net.httpserver package summary outlines the involved classes and contains examples.

    Here's a kickoff example copypasted from their docs (to all people trying to edit it nonetheless, because it's an ugly piece of code, please don't, this is a copy paste, not mine, moreover you should never edit quotations unless they have changed in the original source). You can just copy'n'paste'n'run it on Java 6+.

    package com.stackoverflow.q3732109;
    
    import java.io.IOException;
    import java.io.OutputStream;
    import java.net.InetSocketAddress;
    
    import com.sun.net.httpserver.HttpExchange;
    import com.sun.net.httpserver.HttpHandler;
    import com.sun.net.httpserver.HttpServer;
    
    public class Test {
    
        public static void main(String[] args) throws Exception {
            HttpServer server = HttpServer.create(new InetSocketAddress(8000), 0);
            server.createContext("/test", new MyHandler());
            server.setExecutor(null); // creates a default executor
            server.start();
        }
    
        static class MyHandler implements HttpHandler {
            @Override
            public void handle(HttpExchange t) throws IOException {
                String response = "This is the response";
                t.sendResponseHeaders(200, response.length());
                OutputStream os = t.getResponseBody();
                os.write(response.getBytes());
                os.close();
            }
        }
    
    }
    

    Noted should be that the response.length() part in their example is bad, it should have been response.getBytes().length. Even then, the getBytes() method must explicitly specify the charset which you then specify in the response header. Alas, albeit misguiding to starters, it's after all just a basic kickoff example.

    Execute it and go to http://localhost:8000/test and you'll see the following response:

    This is the response


    As to using com.sun.* classes, do note that this is, in contrary to what some developers think, absolutely not forbidden by the well known FAQ Why Developers Should Not Write Programs That Call 'sun' Packages. That FAQ concerns the sun.* package (such as sun.misc.BASE64Encoder) for internal usage by the Oracle JRE (which would thus kill your application when you run it on a different JRE), not the com.sun.* package. Sun/Oracle also just develop software on top of the Java SE API themselves like as every other company such as Apache and so on. Using com.sun.* classes is only discouraged (but not forbidden) when it concerns an implementation of a certain Java API, such as GlassFish (Java EE impl), Mojarra (JSF impl), Jersey (JAX-RS impl), etc.

    0 讨论(0)
  • 2020-11-22 14:10

    I can strongly recommend looking into Simple, especially if you don't need Servlet capabilities but simply access to the request/reponse objects. If you need REST you can put Jersey on top of it, if you need to output HTML or similar there's Freemarker. I really love what you can do with this combination, and there is relatively little API to learn.

    0 讨论(0)
  • 2020-11-22 14:10

    You may also have a look at some NIO application framework such as:

    1. Netty: http://jboss.org/netty
    2. Apache Mina: http://mina.apache.org/ or its subproject AsyncWeb: http://mina.apache.org/asyncweb/
    0 讨论(0)
提交回复
热议问题