Java实现的一个超轻量级 HTTP 服务器详解编程语言

这是一个直接用 Java 自带的 API 实现的超轻量级的 HTTP 服务器,没有使用第三方类库

import java.io.IOException; 
import java.io.OutputStream; 
import java.net.InetSocketAddress; 
import java.util.Iterator; 
import java.util.List; 
import java.util.Set; 
import java.util.concurrent.Executors; 
  
import com.sun.net.httpserver.Headers; 
import com.sun.net.httpserver.HttpExchange; 
import com.sun.net.httpserver.HttpHandler; 
import com.sun.net.httpserver.HttpServer; 
  
public class HttpServerDemo { 
  public static void main(String[] args) throws IOException { 
    InetSocketAddress addr = new InetSocketAddress(8080); 
    HttpServer server = HttpServer.create(addr, 0); 
  
    server.createContext("/", new MyHandler()); 
    server.setExecutor(Executors.newCachedThreadPool()); 
    server.start(); 
    System.out.println("Server is listening on port 8080" ); 
  } 
} 
  
class MyHandler implements HttpHandler { 
  public void handle(HttpExchange exchange) throws IOException { 
    String requestMethod = exchange.getRequestMethod(); 
    if (requestMethod.equalsIgnoreCase("GET")) { 
      Headers responseHeaders = exchange.getResponseHeaders(); 
      responseHeaders.set("Content-Type", "text/plain"); 
      exchange.sendResponseHeaders(200, 0); 
  
      OutputStream responseBody = exchange.getResponseBody(); 
      Headers requestHeaders = exchange.getRequestHeaders(); 
      Set<String> keySet = requestHeaders.keySet(); 
      Iterator<String> iter = keySet.iterator(); 
      while (iter.hasNext()) { 
        String key = iter.next(); 
        List values = requestHeaders.get(key); 
        String s = key + " = " + values.toString() + "/n"; 
        responseBody.write(s.getBytes()); 
      } 
      responseBody.close(); 
    } 
  } 
}

原创文章,作者:ItWorker,如若转载,请注明出处:https://blog.ytso.com/10956.html

(0)
上一篇 2021年7月19日
下一篇 2021年7月19日

相关推荐

发表回复

登录后才能评论