package web; import com.sun.net.httpserver.Headers; import com.sun.net.httpserver.HttpExchange; import com.sun.net.httpserver.HttpHandler; import com.sun.net.httpserver.HttpServer; import org.springframework.stereotype.Service; import javax.annotation.PostConstruct; import java.io.IOException; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.net.HttpURLConnection; import java.net.InetSocketAddress; /** * Created by zhangbo54 on 2019-01-24. */ @Service public class SimpleServer { @PostConstruct public void initHttpServer() throws IOException { HttpServer server = HttpServer.create(new InetSocketAddress(8418), 0); server.createContext("/test", new MyHandler()); server.setExecutor(null); // creates a default executor server.start(); } static class MyHandler implements HttpHandler { @Override public void handle(HttpExchange httpExchange) throws IOException { System.out.println("receive"); String requestMethod = httpExchange.getRequestMethod(); if (requestMethod.equalsIgnoreCase("GET")) {//客户端的请求是get方法 //设置服务端响应的编码格式,否则在客户端收到的可能是乱码 Headers responseHeaders = httpExchange.getResponseHeaders(); responseHeaders.set("Content-Type", "text/html;charset=utf-8"); //在这里通过httpExchange获取客户端发送过来的消息 //URI url = httpExchange.getRequestURI(); //InputStream requestBody = httpExchange.getRequestBody(); // 这里获取get请求参数 // will return string in format similar to this: "field1=value1&field2=value2&field3=value3..." String queryParams = httpExchange.getRequestURI().getQuery(); System.out.println(queryParams); String response = "this is server"; httpExchange.sendResponseHeaders(HttpURLConnection.HTTP_OK, response.getBytes("UTF-8").length); OutputStream responseBody = httpExchange.getResponseBody(); OutputStreamWriter writer = new OutputStreamWriter(responseBody, "UTF-8"); writer.write(response); writer.close(); responseBody.close(); } } } }
以上所述就是小编给大家介绍的《利用 JavaSE 创建简单 HTTP Server》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!
猜你喜欢:- 如何利用Angular-Cli创建库
- docker利用Dockerfile创建镜像,上传docker hub
- iOS App创建证书,添加Appid,创建配置文件流程
- RabbitMQ集群创建
- 创建哈夫曼树
- RabbitMQ集群创建
本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。
RGB转16进制工具
RGB HEX 互转工具
正则表达式在线测试
正则表达式在线测试