2019-08-25

响应处理


import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.util.Date;

public class Response {
    private BufferedWriter bw;
    // 正文
    private StringBuilder content;
    // 协议头(状态行与响应头)信息
    private StringBuilder headInfo;
    // 正文的字节数
    private int len;

    private final String BLANK = " ";
    private final String CRLF = "\r\n";

    private Response() {
        content = new StringBuilder();
        headInfo = new StringBuilder();
        len = 0;
    }

    public Response(OutputStream os) {
        this();
        bw = new BufferedWriter(new OutputStreamWriter(os));
    }

    public Response(Socket client) {
        this();
        try {
            bw = new BufferedWriter(new OutputStreamWriter(client.getOutputStream()));
        } catch (IOException e) {
            headInfo = null;
            e.printStackTrace();
        }
    }

    // 动态添加内容
    public Response print(String info) {
        content.append(info);
        len += info.getBytes().length;
        return this;
    }

    public Response println(String info) {
        print(info).print(CRLF);
        return this;
    }

    /**
     * 处理中文
     * 
     * @return
     */
    // 推送响应信息
    public void pushToBrowser(int code) throws IOException {
        if (null == headInfo) {
            code = 505;
        }
        creatInfo(code);
        System.out.println(headInfo);
        bw.append(headInfo);
        bw.append(content);
        bw.flush();
    }

    // 构建头信息
    public void creatInfo(int code) {
        // 1.响应行:HTTP/1.1 200 OK
        headInfo.append("HTTP/1.1").append(BLANK).append(code).append(BLANK);
        switch (code) {
            case 200:
                headInfo.append("OK").append(CRLF);
                break;

            case 404:
                headInfo.append("Not Found").append(CRLF);
                break;
            case 505:
                headInfo.append("Server Erro").append(CRLF);
                break;
        }
        // 2.响应头的最后一行存在空
        headInfo.append("Date:").append(new Date()).append(CRLF);
        headInfo.append("Server:Tan Server/39.105.124.213").append(CRLF);
        headInfo.append("Content-type:text/html;charset=UTF-8").append(CRLF);
        headInfo.append("Content-length:").append(len).append(CRLF);
        headInfo.append(CRLF);
    }
}

你可能感兴趣的:(2019-08-25)