码迷,mamicode.com
首页 > 其他好文 > 详细

02-Response简单响应报文

时间:2018-10-18 23:58:05      阅读:303      评论:0      收藏:0      [点我收藏+]

标签:3.2   res   设置   http   text   bytes   buffere   public   day   

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>

 

02-Response简单响应报文

标签:3.2   res   设置   http   text   bytes   buffere   public   day   

原文地址:https://www.cnblogs.com/hua900822/p/9813541.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!