Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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");
    }
}
like image 622
bungler Avatar asked May 03 '26 23:05

bungler


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();
   }
like image 107
Mike Shauneu Avatar answered May 05 '26 13:05

Mike Shauneu


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");
}
like image 36
Nikolas Charalambidis Avatar answered May 05 '26 12:05

Nikolas Charalambidis



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!