Java How to Respond to Httpexchange [Duplicate]

Java How to Respond to Httpexchange [Duplicate]

I am new to Java. I used write server in Golang. I need to send response to the HttpExchange. Here is my code:

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

2 Answers

Handle method in your case should looks like:

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

Use the sendResponseHeaders(int rCode, long responseLength) method. See the documentation and the example:

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

Sarah Jenkins

Sarah Jenkins is a veteran tech journalist with over 12 years of experience covering artificial intelligence, mobile innovations, and digital ethics. Her insights have appeared in leading technology publications worldwide.