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 = "\r\n";
//申请注册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>
05-11 17:27