欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

java httpServer  

程序员文章站 2024-03-22 21:01:10
...

import java.io.IOException;
import java.net.InetSocketAddress;

import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;

/**
 *
 * @author Daniel
 */
public class MyHttpServer {
   
public static void main(String[] args) throws IOException {
        //HttpServer server = HttpServer.create(new InetSocketAddress("127.0.0.1", 80), 0);
        HttpServer server =HttpServer.create(new InetSocketAddress(6666), 100);
        server.createContext("/myApp", new MyResponseHandler());  
        server.setExecutor(null); // creates a default executor
        server.start();
        System.out.println("OK");
    }
public static class MyResponseHandler implements HttpHandler {
    @Override
    public void handle(HttpExchange t) throws IOException {
        String response = "http://www.google.com";
        t.getResponseHeaders().add("location", response);
        t.sendResponseHeaders(403, response.length());
        t.close();       
    }
}
}