Java服务端使用HttpServer处理Http请求

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_29125669/article/details/77873923

转载请注明出处:http://blog.csdn.net/qq_29125669/article/details/77873923

Java服务端处理Http请求

以前用Java都是编写客户端发送http请求,这次有需求做一个服务端接收客户端的http请求,并以http标准格式返回数据。在网上搜了一会,大部分都是用socket写的服务端,不符合需求。Java其实提供了一个HttpServer可以处理客户端的http请求。做个记录,省得以后需要还要去网上搜半天。

主要代码如下:

 public class HttpServerDemo {   
    public static void main(String[] args) throws IOException {
        HttpServerProvider provider = HttpServerProvider.provider();  
        HttpServer httpserver =provider.createHttpServer(new InetSocketAddress(19017), 100);//监听端口19017,能同时接受100个请求  
        httpserver.createContext("/", new MyResponseHandler());   
        httpserver.setExecutor(null);  
        httpserver.start();  
        System.out.println("server started");  
    }
    public static class MyResponseHandler 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();

                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();  
            }  

        }
    }

花时间最多的是在设置响应头的编码格式上面,网上的例子都没有介绍到,如果不设置编码格式,用浏览器发起http请求时,接收到的返回值可能是乱码。

展开阅读全文

没有更多推荐了,返回首页