간단 한 http 시 뮬 레이 터 구현

6870 단어 socket
/**
 * http   
 *     http     http  
 */

public class HttpSimulator
{
    //  
    private String host = "localhost";
    //  
    private int port = 80;
    //   post    
    private boolean isPost;
    //   head    
    private boolean isHead;
    //             
    private StringBuilder requestMessage = new StringBuilder();
    private Socket socket;
    //   
    private static final String LINE_SEPARATOR = System.getProperty("line.separator");

    public void run() throws IOException
    {
        BufferedReader consoleReader = new BufferedReader(new InputStreamReader(System.in));
        try
        {
            while (true)
            {
                //  host port
                if (!readRequestHostAndPort(consoleReader))
                    return;
                //  http request
                readHttpRequest(consoleReader);
                //  http request
                sendHttpRequest();
                //  http response
                readHttpResponse(consoleReader);
            }
        }
        finally
        {
            if (consoleReader != null)
            {
                try
                {
                    consoleReader.close();
                }
                catch (Exception e)
                {
                    e.printStackTrace();
                }
            }
        }
    }

    private boolean readRequestHostAndPort(BufferedReader consoleReader) throws IOException
    {
        System.out.print("host:port>");
        String content = consoleReader.readLine();

        if ("q".equals(content))
            return false;

        //  host port             
        String[] parts = content.split(":");
        String host_str = parts[0].trim();
        if (host_str.length() > 0)
            host = host_str;
        if (parts.length > 1)
            port = Integer.parseInt(parts[1].trim());
        return true;
    }

    private void readHttpRequest(BufferedReader consoleReader) throws IOException
    {
        System.out.println("-----------------Request Header-----------------");
        String content = consoleReader.readLine();

        //             POST? HEAD?
        requestMessage.append(content).append(LINE_SEPARATOR);
        String[] parts = content.split(" +");
        String method = parts[0].trim();
        isPost = "POST".equals(method);
        isHead = "HEAD".equals(method);

        //                 ""     
        while (!"".equals(content = consoleReader.readLine()))
            requestMessage.append(content).append(LINE_SEPARATOR);
        requestMessage.append(LINE_SEPARATOR);

        //   post            
        if (isPost)
        {
            while (!"".equals(content = consoleReader.readLine()))
                requestMessage.append(content).append(LINE_SEPARATOR);
        }
    }

    private void sendHttpRequest() throws IOException
    {
        socket = new Socket();
        System.out.println("connecting " + host + ":" + port);
        //  read  3000  
        socket.setSoTimeout(3000);
        //      5000  
        socket.connect(new InetSocketAddress(host, port), 5000);

        //  http  
        PrintWriter out = new PrintWriter(socket.getOutputStream());
        out.println(requestMessage.toString());
        out.flush();
        socket.shutdownOutput();
        //       http  
        requestMessage.delete(0, requestMessage.length());
    }

    private void readHttpResponse(BufferedReader consoleReader) throws IOException
    {
        BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
        String line = null;
        boolean headReaded = false;
        System.out.println("-----------------Response Header-----------------");
        try
        {
            //      (   、   、   )
            while (null != (line = in.readLine()))
            {
                //  ""           headReaded   true    HEAD          
                if ("".equals(line) && !headReaded && !isHead)
                {
                    System.out.print("Show Data? ");
                    String confirm = consoleReader.readLine();
                    headReaded = true;
                    if ("Y".equals(confirm.toUpperCase()))
                    {
                        System.out.println("-----------------HTTP Response Data-----------------");
                        System.out.println(line);
                        continue;
                    }
                    else
                        break;
                }
                else
                {
                    System.out.println(line);
                }
            }
        }
        finally
        {
            socket.close();
        }
    }

    public static void main(String[] args) throws IOException
    {
        new HttpSimulator().run();
    }
}

실행 결과:
host:port>localhost:8080
-----------------Request Header-----------------
GET /test_web/test.html HTTP/1.1
Host:

connecting localhost:8080
-----------------Response Header-----------------
HTTP/1.1 200 OK
Server: Apache-Coyote/1.1
Accept-Ranges: bytes
ETag: W/"259-1397034177525"
Last-Modified: Wed, 09 Apr 2014 09:02:57 GMT
Content-Type: text/html
Content-Length: 259
Date: Tue, 15 Apr 2014 07:22:38 GMT
Show Data? y
-----------------HTTP Response Data-----------------

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
      
</body>
</html>
host:port>

좋은 웹페이지 즐겨찾기