ng"/>
【弄nèng
文章目录
- 1. pom
- 2. 服务端
- 3. 处理器
- 测试
- 源码地址
- 项目推荐
Httpserver 适用于构建功能单一简单的WEB服务。例如机器代理,用Spring之类的框架显得臃肿,没那么必要。
参考:.html
1. pom
<!--io--><dependency><groupId>commons-io</groupId><artifactId>commons-io</artifactId><version>2.5</version></dependency>
2. 服务端
import com.sun.httpserver.HttpServer;
import java.io.IOException;
import java.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.httpserver.HttpServer.create(new InetSocketAddress(8000), backLog);} catch (IOException e) {e.printStackTrace();}server.createContext("/test", new JobHandler());server.start();}}
3. 处理器
import com.sun.httpserver.HttpExchange;
import com.sun.httpserver.HttpHandler;
import org.apachemons.io.IOUtils;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.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";@Overridepublic void handle(HttpExchange exchange) throws IOException {// 该命令可能在新的线程、已入池的线程或者正调用的线程中执行,这由 Executor 实现决定。fixedThreadPool.execute(new Runnable() {@Overridepublic 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服务管理平台,集成基础服务,中间件服务,监控告警服务等
更多推荐
【弄nèng
发布评论