GROOVY:如何使用serverSocket仅写入GET请求?

问题描述 投票:-1回答:1

我想创建一个套接字,该套接字将仅对GET请求答复200 OK,对其他方法答复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'
                        }
                    }
                }
            }
    }
}
sockets groovy serversocket http-method
1个回答
0
投票

您可以使用Java中包含的内部sun http服务器来解析http请求并建立响应

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 ReverseHandler())
                //createContext('/groovy/', new GroovyReverseHandler())
                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 ReverseHandler 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());
            }
        }
    }
}

© www.soinside.com 2019 - 2024. All rights reserved.