GROOVY:如何使用serverSocket仅写入GET请求? [英] GROOVY: how to write only GET request using serverSocket?

查看:81
本文介绍了GROOVY:如何使用serverSocket仅写入GET请求?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want to create a socket that will reply to me 200 OK only to GET request and reply 500 to other methods. Input returns me lines and the first one has the name of method. I can't understand how to match GET with such an output.

    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'
                        }
                    }
                }
            }
    }
}

推荐答案

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

you could use internal sun http server included in java to parse http-request and build response

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());
            }
        }
    }
}

这篇关于GROOVY:如何使用serverSocket仅写入GET请求?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆