【问题标题】:Java how to respond to HttpExchange [duplicate]Java如何响应HttpExchange [重复]
【发布时间】:2018-05-21 16:18:56
【问题描述】:

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

【问题讨论】:

标签: java sockets jakarta-ee httpserver


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-07-22
      • 2015-08-23
      • 2019-07-19
      • 2013-04-09
      • 1970-01-01
      • 1970-01-01
      • 2021-02-27
      • 2023-04-03
      相关资源
      最近更新 更多