HttpServerProvider实现http服务接口(一)

时间:2022-09-11 21:40:50

啥也不说了,直接上代码,简单的示例。

 

服务端代码:

package dyan.server;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.InetSocketAddress;

import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;
import com.sun.net.httpserver.spi.HttpServerProvider;


public class DealMain
{
    
    public static void main(String[] args) throws Exception
    {
        HttpServerProvider provider = HttpServerProvider.provider();
        
        HttpServer server = provider.createHttpServer(new InetSocketAddress(6688), 10);
        
        server.createContext("/dyan", new DealMain().new DyanHttpHandler());
        
        server.setExecutor(null);
        server.start();
        
    }
    
    
    class DyanHttpHandler implements HttpHandler
    {

        @Override
        public void handle(HttpExchange arg0) throws IOException
        {
            System.out.println("accept an exchange from internet.....");
            
            String resp = "your request message i get it!";
            
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(arg0.getRequestBody()));
            
            System.out.println(bufferedReader.readLine());
            
            arg0.sendResponseHeaders(200, resp.getBytes().length);
            
            OutputStream out = arg0.getResponseBody();
            out.write(resp.getBytes());
            
            out.flush();
            arg0.close();
        }
        
    }
    
}

 

 

请求代码:

 public static void main(String[] args) throws Exception
    {
        URL url = null;
        HttpURLConnection urlConnection = null;
        
        url = new URL("http://localhost:6688/dyan");
        urlConnection = (HttpURLConnection)url.openConnection();
        
        urlConnection.setRequestMethod("POST");
        urlConnection.setDoInput(true);
        urlConnection.setDoOutput(true);
        urlConnection.setUseCaches(false);
        
        System.out.println("begin send parameters....");
        
        urlConnection.getOutputStream().write("i am dyan".getBytes());
        urlConnection.getOutputStream().flush();
        urlConnection.getOutputStream().close();
        
        InputStream in = urlConnection.getInputStream();
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(in));
        
        System.out.println(bufferedReader.readLine());
        
        bufferedReader.close();
        
        
        urlConnection.disconnect();
    }

 

先执行服务端代码,将服务端启动起来,来接收请求。

再执行请求代码,发起请求。

控制台打印信息如下:

  1、请求端

begin send parameters....
your request message i get it!

 

  2、服务端

accept an exchange from internet.....
i am dyan

 

运行原理见:HttpServerProvider实现http服务接口(二)