Java服务器http怎么写?Java写服务器http代码

Java是目前比较流行的开发语言,很多项目的开发都可以使用java语言,使用java可以开发小游戏、网页等,那Java服务器http怎么写?下面来我们就来给大家讲解一下。

主程序类

package bg.httpserver;
import com.sun.net.httpserver.HttpServer;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.util.concurrent.Executors;
public class HttpServerStarter
{
    public static void main(String[] args) throws IOException
    {
        //创建一个HttpServer实例,并绑定到指定的IP地址和端口号
        HttpServer httpServer = HttpServer.create(new InetSocketAddress(8080), 0);
        //创建一个HttpContext,将路径为/myserver请求映射到MyHttpHandler处理器
        httpServer.createContext("/myserver", new MyHttpHandler());
        //设置服务器的线程池对象
        httpServer.setExecutor(Executors.newFixedThreadPool(10));
        //启动服务器
        httpServer.start();
    }
}

HttpServer:HttpServer主要是通过带参的create方法来创建,第一个参数InetSocketAddress表示绑定的ip地址和端口号。第二个参数为int类型,表示允许排队的最大TCP连接数,如果该值小于或等于零,则使用系统默认值。

createContext:可以调用多次,表示将指定的url路径绑定到指定的HttpHandler处理器对象上,服务器接收到的所有路径请求都将通过调用给定的处理程序对象来处理。

setExecutor:设置服务器的线程池对象,不设置或者设为null则表示使用start方法创建的线程。

HttpHandler实现

package bg.httpserver;
import com.sun.net.httpserver.Headers;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
/**
* 处理/myserver路径请求的处理器类
*/
public class MyHttpHandler implements HttpHandler
{
    @Override
    public void handle(HttpExchange httpExchange)
        {
            try
            {
                StringBuilder responseText = new StringBuilder();
                responseText.append("请求方法:")
                    .append(httpExchange.getRequestMethod())
                    .append("
                        ");
                        responseText.append("请求参数:")
                        .append(getRequestParam(httpExchange))
                        .append("
                            ");
                            responseText.append("请求头:
                                ").append(getRequestHeader(httpExchange));
                                handleResponse(httpExchange, responseText.toString());
                            }
                            catch (Exception ex)
                            {
                                ex.printStackTrace();
                            }
                        }
                        /**
                        * 获取请求头
                        * @param httpExchange
                        * @return
                        */
                        private String getRequestHeader(HttpExchange httpExchange)
                        {
                            Headers headers = httpExchange.getRequestHeaders();
                            return headers.entrySet()
                                .stream()
                                .map((Map.Entry < string, list > entry) - > entry.getKey() + ":" + entry.getValue()
                                    .toString())
                                .collect(Collectors.joining("
                                        "));
                                    }
                                    /**
                                    * 获取请求参数
                                    * @param httpExchange
                                    * @return
                                    * @throws Exception
                                    */
                                    private String getRequestParam(HttpExchange httpExchange) throws Exception
                                    {
                                        String paramStr = "";
                                        if (httpExchange.getRequestMethod()
                                            .equals("GET"))
                                        {
                                            //GET请求读queryString
                                            paramStr = httpExchange.getRequestURI()
                                                .getQuery();
                                        }
                                        else
                                        {
                                            //非GET请求读请求体
                                            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(httpExchange.getRequestBody(), "utf-8"));
                                            StringBuilder requestBodyContent = new StringBuilder();
                                            String line = null;
                                            while ((line = bufferedReader.readLine()) != null)
                                            {
                                                requestBodyContent.append(line);
                                            }
                                            paramStr = requestBodyContent.toString();
                                        }
                                        return paramStr;
                                    }
                                    /**
                                    * 处理响应
                                    * @param httpExchange
                                    * @param responsetext
                                    * @throws Exception
                                    */
                                    private void handleResponse(HttpExchange httpExchange, String responsetext) throws Exception
                                    {
                                        //生成html
                                        StringBuilder responseContent = new StringBuilder();
                                        responseContent.append("")
                                            .append("")
                                            .append(responsetext)
                                            .append("")
                                            .append("");
                                        String responseContentStr = responseContent.toString();
                                        byte[] responseContentByte = responseContentStr.getBytes("utf-8");
                                        //设置响应头,必须在sendResponseHeaders方法之前设置!
                                        httpExchange.getResponseHeaders()
                                            .add("Content-Type:", "text/html;charset=utf-8");
                                        //设置响应码和响应体长度,必须在getResponseBody方法之前调用!
                                        httpExchange.sendResponseHeaders(200, responseContentByte.length);
                                        OutputStream out = httpExchange.getResponseBody();
                                        out.write(responseContentByte);
                                        out.flush();
                                        out.close();
                                    }
                                }

HttpExchange:用于获取请求内容以及生成和发送响应。

运行HttpServerStarter,在浏览器中访问如下:

Java服务器http怎么写?Java写服务器http代码.jpg

其实java实现服务器http还是很简单的,在Java中我们可以使用HttpServer类来实现Http服务器,如果大家刚感兴趣的话,可以自己尝试开发一下哦!最后大家如果想要了解更多java实例知识,敬请关注奇Q工具网。

推荐阅读:

java初级中级高级怎么评定的?java等级评定方法

json在线解析器是干嘛的?json解析方法有哪些?

高级java面试题有哪些?高级java面试题大全