Java 如何响应HttpExchange

Java how to respond to HttpExchange

我是 Java 的新手。我在 Golang 中使用了写入服务器。我需要向 HttpExchange 发送回复。这是我的代码:

public static void main(String[] args) throws IOException 
{
  Server = HttpServer.create(new InetSocketAddress(8000),0);
  Server.createContext("/login", new SimpleHandler());
  Server.setExecutor(null);
  Server.start();
}
class SimpleHandler implements HttpHandler
{
    @Override
    public void handle(HttpExchange request) throws IOException 
    {
     //Here I need to do like request.Response.Write(200,"DONE");
    }
}

使用sendResponseHeaders(int rCode, long responseLength)方法。请参阅 documentation 和示例:

@Override
public void handle(HttpExchange request) throws IOException {
     request.sendResponseHeaders(200, "DONE");
}

您的处理方法应如下所示:

    public void handle(HttpExchange request) throws IOException
    {
        byte[] response = "DONE".getBytes();
        e.sendResponseHeaders(200, response.length);
        OutputStream os = e.getResponseBody();
        os.write(response);
        os.close();
   }