java httpserver

 
//start
import java.io.IOException;
import java.net.InetSocketAddress;
import java.util.concurrent.Executors;

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


public class HttpDemo {
    private HttpServer ser ;
    private int port=8080;
    public HttpDemo() {
        // TODO Auto-generated constructor stub
        try {
            ser = HttpServer.create(new InetSocketAddress(port), 0);
            ser.createContext("/",new DataHandler());
            ser.setExecutor(Executors.newCachedThreadPool());
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
       
    }
    public void work(){
        ser.start();
        System.out.println("My Proxy server started!");
        System.out.println("Listing port :"+port);
    }
    public static void main(String[] args) {
        new HttpDemo().work();
    }
}

//end
//start
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.URI;
import java.net.URL;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

import com.sun.corba.se.impl.encoding.CodeSetConversion.BTCConverter;
import com.sun.net.httpserver.Headers;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;


public class DataHandler implements HttpHandler{
    public void handle(HttpExchange exchange) throws IOException {
        // TODO Auto-generated method stub
        String method = exchange.getRequestMethod();
        if (method.equalsIgnoreCase("GET")){
            URI uri=exchange.getRequestURI();
            String pro = exchange.getProtocol();
            System.out.println("connect:");
            Headers respons = exchange.getResponseHeaders();
            respons.set("Content-Type", "text/html");
            Headers request = exchange.getRequestHeaders();
            String host=request.getFirst("Host");
            System.out.println(pro+host+uri);
            Set<String> keyset = request.keySet();
            Iterator<String> ite = keyset.iterator();
            String info="";
            while(ite.hasNext()){
                String key = ite.next();
                String val = request.getFirst(key);
                String str = key+" == "+val+"\n";
                System.out.printf(str);
                info+=str;
            }
            String data="<html><head></head><body><h1>hello world</h1><div><pre>"+info+"</pre></div></body></html>";
            exchange.sendResponseHeaders(200, data.length());
            OutputStream out = exchange.getResponseBody();
            out.write(data.getBytes());
            out.close();
        }
       
    }
}

//end

你可能感兴趣的:(java,server,String,Class,Exchange,Constructor)