【弄nèng - HttpServer】使用Java内置的Http Server构建Web应用

Httpserver 适用于构建功能单一简单的WEB服务。例如机器代理,用Spring之类的框架显得臃肿,没那么必要。

参考:https://www.cnblogs.com/aspwebchh/p/8300945.html
https://www.jianshu.com/p/74db02eeb710

1. pom

        <!--io-->
        <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>2.5</version>
        </dependency>

2. 服务端

import com.sun.net.httpserver.HttpServer;
import java.io.IOException;
import java.net.InetSocketAddress;

/**
 * @author 司马缸砸缸了
 * @date 2019/8/2 10:50
 * @description server
 */
public class HttpServerMain {

    public static void main(String[] args) {
        //允许最大连接数
        int backLog = 100;
        HttpServer server = null;
        try {
            server = com.sun.net.httpserver.HttpServer.create(new InetSocketAddress(8000), backLog);
        } catch (IOException e) {
            e.printStackTrace();
        }

        server.createContext("/test", new JobHandler());
        server.start();
    }



}

3. 处理器

import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import org.apache.commons.io.IOUtils;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 *  处理器
 * 
 * @author 司马缸砸缸了
 * @date 2019/8/2 11:08
 * @description
 */
public class JobHandler implements HttpHandler {
    /**
     * 处理线程池
     */
    private ExecutorService fixedThreadPool = Executors.newFixedThreadPool(100);
    /**
     * 响应格式
     */
    private final static String APPLICATION_JSON = "application/json;charset=UTF-8";
    private final static String TEXT_PLAIN = "text/plain;charset=UTF-8";

    @Override
    public void handle(HttpExchange exchange) throws IOException {

        // 该命令可能在新的线程、已入池的线程或者正调用的线程中执行,这由 Executor 实现决定。
        fixedThreadPool.execute(new Runnable() {
            @Override
            public void run() {
                //获得查询字符串(get)
                String queryString = exchange.getRequestURI().getQuery();
                Map<String, String> queryStringInfo = formData2Dic(queryString);
                //获得表单提交数据(post)
                String postString = null;
                try {
                    postString = IOUtils.toString(exchange.getRequestBody());
                } catch (IOException e) {
                    e.printStackTrace();
                }
                Map<String, String> postInfo = formData2Dic(postString);

                //返回
                String response = "hello httpserver";
                // 响应
                writeResponse(exchange, response, APPLICATION_JSON);
            }
        });
    }

    /**
     * 响应
     *
     * @param httpExchange
     * @param response
     * @param contentType
     */
    private static void writeResponse(HttpExchange httpExchange, String response, String contentType) {
        if (contentType != null) {
            httpExchange.getResponseHeaders().set("Content-Type", contentType);
        }
        try {
            //设置响应头
            httpExchange.sendResponseHeaders(200, response.length());
        } catch (IOException e) {
            e.printStackTrace();
        }

        OutputStream os = httpExchange.getResponseBody();
        try {
            os.write(response.getBytes());
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                os.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }


    /**
     * 解析参数
     *
     * @param formData
     * @return
     */
    public static Map<String, String> formData2Dic(String formData) {
        Map<String, String> result = new HashMap<>();
        if (formData == null || formData.trim().length() == 0) {
            return result;
        }
        final String[] items = formData.split("&");
        Arrays.stream(items).forEach(item -> {
            final String[] keyAndVal = item.split("=");
            if (keyAndVal.length == 2) {
                try {
                    final String key = URLDecoder.decode(keyAndVal[0], "utf8");
                    final String val = URLDecoder.decode(keyAndVal[1], "utf8");
                    result.put(key, val);
                } catch (UnsupportedEncodingException e) {
                }
            }
        });
        return result;
    }

}

测试

浏览器访问:http://localhost:8000/test

结果:
在这里插入图片描述

源码地址

传送门
开源项目,持续不断更新中,喜欢请 Star~

项目推荐

IT-CLOUD :IT服务管理平台,集成基础服务,中间件服务,监控告警服务等

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值