02-Response简单响应报文

Posted hua900822

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了02-Response简单响应报文相关的知识,希望对你有一定的参考价值。

package com.day5;

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

public class Server {

    /**刘诗华 Response响应
     * @param args
     * @throws Exception 
     */
    public static void main(String[] args) throws Exception {
        
        //设置换行符
        String CRLF = "
";
        //申请注册8080套接字        
        ServerSocket server=new ServerSocket(8080);
        
        System.out.println("开始接受请求...");
        //接受客户端请求
        Socket socket = server.accept();
        //获取客户端对象输出流对象
        OutputStream out = socket.getOutputStream();
        //将字节输出流转换成字符输出流
        OutputStreamWriter writer = new OutputStreamWriter(out);
        //将字符输出流转换成缓冲字符流
        BufferedWriter bw = new BufferedWriter(writer);
        
        StringBuilder response=new StringBuilder();
        
        //响应报文主体内容
        String html="<h1>Hello my name is liu shi hua</h1>";
        
        //设置响应头信息
        response.append("HTTP/1.1 200 OK").append(CRLF);
        response.append("Server:Apache/2.4.10 (Win32) php/5.3.28").append(CRLF);
        response.append("Date:").append(new Date()).append(CRLF);
        response.append("Content-Type:text/html").append(CRLF);
        response.append("Content-Length: "+html.getBytes().length).append(CRLF);
        response.append(CRLF);
        response.append(html);
        
        //发送数据到客户端
        bw.write(response.toString());
        
        //关闭资源流
        bw.close();
        socket.close();
        server.close();
        
        System.out.println(response);
        
    }

}

 

响应报文格式

HTTP/1.1 200 OK
Server:Apache/2.4.10 (Win32) PHP/5.3.28
Date:Fri, 06 Jul 2018 14:52:32 GMT
Content-Type:text/html
Content-Length: 17

<h1>Hello</h1>

 

以上是关于02-Response简单响应报文的主要内容,如果未能解决你的问题,请参考以下文章

HTTP请求报文和响应报文

HTTP结构

读《图解HTTP》有感-(简单的HTTP协议)

VSCode自定义代码片段—— 数组的响应式方法

VSCode自定义代码片段10—— 数组的响应式方法

HTTP协议浅析(中):请求报文和响应报文