【问题标题】:GROOVY: how to write only GET request using serverSocket?GROOVY:如何使用 serverSocket 只编写 GET 请求?
【发布时间】:2020-02-26 00:43:15
【问题描述】:

我想创建一个套接字,它只回复我200 OKGET 请求并回复500 到其他方法。 输入返回我的行,第一个具有方法的名称。我不明白如何将GET 与这样的输出相匹配。

    static void main(String[] args) {

        def ss = new ServerSocket(1234)
        new File("OuTsocket.txt")

            while (true) {
                ss.accept { sock ->
                    sock.withStreams { input, output ->

                        output.withWriter { writer ->
                            writer << "HTTP/1.1 200 OK\n"
                            writer << "Content-Type: application/json\n\n"
                            writer << '{"Name": "Anna"}\n'
                        }
                    }
                }
            }
    }
}

【问题讨论】:

  • 您本质上是在询问 HTTP 协议是如何工作的,即请求的外观以及您在其中找到请求方法的位置。有a standard for that 是有原因的。至少看看Wikipedia article to HTTP 这是一个很好的总结。请注意,您的 HTTP 响应也是错误的(至少文件结尾错误)。

标签: sockets groovy serversocket http-method


【解决方案1】:

您可以使用 java 中包含的内部 sun http 服务器来解析 http-request 并构建响应

import com.sun.net.httpserver.*
import java.util.concurrent.Executors
import groovy.json.*

public class Web2{
    private static int HTTP_SERVER_PORT=8000;

    public static void log(String s){
        println "${new Date().format('yyyy-MM-dd HH:mm:ss.SSS')} $s"
    }


    public static void main(String[]arg){
        try {
            InetSocketAddress addr = new InetSocketAddress(HTTP_SERVER_PORT);
            def httpServer = com.sun.net.httpserver.HttpServer.create(addr, 0)

            httpServer.with {
                createContext('/', new MyHttpHandler())
                setExecutor(Executors.newCachedThreadPool())
                start()
                log "server started.";
                log "endpoint: http://${java.net.InetAddress.getLocalHost().getHostName()}:$HTTP_SERVER_PORT/"
            }
        }catch(e){
            log "Error starting server:\n\t$e\n"
            log "press any key to continue..."
            System.in.read()
        }
    }

    static class MyHttpHandler implements HttpHandler {
        public void handle(HttpExchange httpExchange) throws IOException{
            def id = Long.toString(httpExchange.hashCode(),36).padLeft(8,'0')
            try {
                log "[$id] handle - start";
                String requestMethod = httpExchange.getRequestMethod();
                log "[$id] method : $requestMethod"
                log "[$id] headers: ${httpExchange.getRequestHeaders().toString()}"
                if (requestMethod.equalsIgnoreCase("GET")) {
                    Headers responseHeaders = httpExchange.getResponseHeaders();
                    responseHeaders.set("Content-Type", "application/json");
                    httpExchange.sendResponseHeaders(200, 0);

                    httpExchange.getResponseBody().withWriter("UTF-8"){w->
                        def respData = httpExchange.getRequestHeaders() //just example as json data to send back
                        new JsonBuilder(respData).writeTo(w)
                    }
                } else {
                    throw new Exception("not supported")
                }
                httpExchange.close();
                log "[$id] response sent";
            }catch(Throwable e){
                log "[$id] $e"
                try{
                    httpExchange.sendResponseHeaders(500, 0);
                    responseHeaders.set("Content-Type", "text/plain");
                }catch(ei){}
                httpExchange.getResponseBody().write(e.toString().getBytes());
            }
        }
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-09-03
    • 2016-05-27
    • 2019-08-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多