Java实现http服务器(一)

基于Java实现Http服务器有多种多样的方法

一种轻量级的方式是使用JDK内置的com.sun.net.httpserver包下和sun.net.httpserver包下类提供的方法构建,该方法轻便快捷。

import java.io.IOException;
import java.net.InetSocketAddress;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import com.sun.net.httpserver.HttpServer;

/**
 * @author 作者 E-mail:
 * @version 创建时间:2015-10-24 下午04:51:40 类说明
 */
public class HttpServerManager
{
    private final  static HttpServerManager instance = new HttpServerManager();

    private HttpServer httpServer = null;

    private ExecutorService executor = null;

    private HttpServerManager()
    {

    }

    public final static HttpServerManager getInstance()
    {
        return instance;
    }

    public final void init() throws IOException
    {
        this.executor = Executors.newCachedThreadPool();
        final InetSocketAddress sa = new InetSocketAddress("0.0.0.0", 8080);
        this.httpServer = HttpServer.create(sa, 0);
        this.httpServer.setExecutor(this.executor);
        this.httpServer.createContext("/", new HttpServerHandler());
        this.httpServer.start();
    }

    public final void exit()
    {
        this.executor.shutdown();
        this.httpServer.stop(0);
    }
}

 

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.URI;

import com.sun.net.httpserver.Headers;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.ssl.HttpsURLConnection;

/**
 * @author 作者 E-mail:
 * @version 创建时间:2015-10-24 下午05:02:25 类说明
 */
public class HttpServerHandler implements HttpHandler
{
    public void onError(HttpExchange exchange) throws IOException
  {
    exchange.sendResponseHeaders(HttpsURLConnection.HTTP_BAD_REQUEST,0);
    exchange.getResponseBody().close();
  }

  public static String getQueryString(HttpExchange exchange) throws IOException
    {
        
        if (exchange.getRequestMethod().equalsIgnoreCase("GET"))
        {
            return exchange.getRequestURI().getQuery();
        }

        String requestBodyString = getRequestBodyString(exchange);

        if (requestBodyString.length() == 0)
        {
            return exchange.getRequestURI().getQuery();
        }
        return requestBodyString;
    }

    public static String getRequestBodyString(HttpExchange exchange) throws IOException
    {
        BufferedReader br = new BufferedReader(new InputStreamReader(exchange.getRequestBody(), "UTF-8"));
        StringBuilder builder = new StringBuilder();
        String line = null;
        while ((line = br.readLine()) != null)
        {
            builder.append(line);
        }

        return builder.toString();
    }

    @SuppressWarnings("deprecation")
    @Override
    public void handle(HttpExchange exchange) throws IOException
    {
        OutputStream os = null;
        final URI uri = exchange.getRequestURI();
        //http://127.0.0.1:8080/cmd/helloWorld
        final String path = uri.getPath();
        final String query = getQueryString(exchange);
        final Headers responseHeaders = exchange.getResponseHeaders();
        // 返回结果
        final byte[] result = new byte[] { ' ', ' ' };

        responseHeaders.set("Content-Type", "text/plain");
        responseHeaders.set("Content-length", String.valueOf(result.length));

        exchange.sendResponseHeaders(HttpsURLConnection.HTTP_OK, 0);
        os = exchange.getResponseBody();
        os.write(result);
        
        os.close();
    }
}

  

  

再举一个使用jdk自带httpserver组件的例子:

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;  
//在eclipse中会出现Access restriction: The type Headers is not accessible due to restriction on required library  
//解决办法:把Windows-Preferences-Java-Complicer- Errors/Warnings里面的Deprecated and restricted API中的Forbidden references(access rules)选为Warning就可以编译通过。  
/** 
 * 使用jdk自带sun httpserver组件构建Http服务器, 
 * JDK自带的HttpServer是一个非常轻量级的Http服务端框架,但是它非常灵活,易于扩展, 
 * @author Administrator 
 * 
 */  
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();  
        System.out.println("处理新请求:"+requestMethod);  
        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();  
        }  
    }  
} 
    原文作者:无心流泪
    原文地址: https://www.cnblogs.com/wuxinliulei/p/4923948.html
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞