Java如何响应HttpExchange

时间:2017-12-07 14:18:45

标签: java

我是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");
    }
}

2 个答案:

答案 0 :(得分:1)

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

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

答案 1 :(得分:1)

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

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