package cn.edu.sss.httpServer;

import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.util.Date; //这个类是对http协议返回的封装 public class HttpResponse { public final String CRLF="\r\n";
public final String BLANK=" "; //返回正文的长度
private int len;
//返回状态行和请求头信息
private StringBuilder head; //返回正文内容
private StringBuilder content; //用于写到输出流中
private BufferedWriter bw; private HttpResponse()
{
len=0;
content=new StringBuilder();
head=new StringBuilder(); }
public HttpResponse(Socket s)
{
this();
try {
bw=new BufferedWriter(new OutputStreamWriter(s.getOutputStream()));
} catch (IOException e) {
// TODO Auto-generated catch block
head=null;
e.printStackTrace();
} } //构建正文
public void print(String s)
{
content.append(s);
len=content.toString().getBytes().length; }
public void println(String s)
{
content.append(s).append(CRLF);
len=content.toString().length(); } /*
private void createHeadInfo(int code){
//1) HTTP协议版本、状态代码、描述
headInfo.append("HTTP/1.1").append(BLANK).append(code).append(BLANK);
switch(code){
case 200:
headInfo.append("OK");
break;
case 404:
headInfo.append("NOT FOUND");
break;
case 505:
headInfo.append("SEVER ERROR");
break;
}
headInfo.append(CRLF);
//2) 响应头(Response Head)
headInfo.append("Server:bjsxt Server/0.0.1").append(CRLF);
headInfo.append("Date:").append(new Date()).append(CRLF);
headInfo.append("Content-type:text/html;charset=GBK").append(CRLF);
//正文长度 :字节长度
headInfo.append("Content-Length:").append(len).append(CRLF);
headInfo.append(CRLF); //分隔符
}
//推送到客户端
*/
private void createHeader(int code)
{
head.append("HTTP/1.1").append(BLANK).append(code).append(BLANK);
switch(code)
{
case 200:
head.append("OK");break;
case 404:
head.append("NOT FOUND"); }
head.append(CRLF);
head.append("Server:tomcat").append(CRLF);
head.append("Date:").append(new Date()).append(CRLF);
head.append("Content-type:text/html;charset=GBK").append(CRLF);
head.append("Content-Length:").append(len).append(CRLF);
head.append(CRLF); }
public void flush(int code) throws IOException
{ createHeader(code);
bw.write(head.toString());
bw.write(content.toString());
bw.flush(); } public static void main(String[] args) {
// TODO Auto-generated method stub } }
HTTP/1.1  OK

Server:Apache Tomcat/5.0.

Date:Mon,6Oct2003 :: GMT

Content-Length:

好了,我们测试一下httpResponse的用法

package cn.edu.sss.httpServer;

import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Date; public class ServerDemo1 {
public static final String BLANK=" ";
public static final String CRLF="\r\n"; public static void main(String args[]) throws IOException
{
ServerSocket server=new ServerSocket(8088);
Socket socket=server.accept();
byte[] bytes=new byte[20000];
System.out.println(socket.getInetAddress());
int len=socket.getInputStream().read(bytes);
String request=new String(bytes,0,len);
System.out.println(request); HttpResponse response=new HttpResponse(socket);
response.print("<html><head><titilt>你怎么舍得我难过</title>大姑娘美,大姑娘浪</head><body></body></html>");
response.flush(200);//指明响应码 /*
//下面构造响应正文
StringBuilder sbu=new StringBuilder(); sbu.append("<html><head><titilt>你怎么舍得我难过</title>大姑娘美,大姑娘浪</head><body></body></html>");
//
StringBuilder response=new StringBuilder();
response.append("HTTP/1.1").append(BLANK).append("200").append(BLANK).append("OK").append(CRLF);
//响应头
response.append("Server: tomcat").append(CRLF);
response.append("Date").append(new Date()).append(CRLF);
response.append("Content-type:text/html;charset=GBK").append(CRLF);
//正文长度,字节长度
response.append("Content-Length:").append(sbu.toString().getBytes().length).append(CRLF); response.append(CRLF);
//加入正文
response.append(sbu); System.out.println(response); //返回给服务器端 BufferedWriter buf=new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
buf.write(response.toString());
buf.flush();;
buf.close();
*/ } }

现在我们测试一下:在浏览器中输入网址

localhost:8088

会返回我们的网页,你可以试试

自己手写http服务器 http响应信息的封装与测试的更多相关文章

  1. JavaSE 手写 Web 服务器(二)

    原文地址:JavaSE 手写 Web 服务器(二) 博客地址:http://www.extlight.com 一.背景 在上一篇文章 <JavaSE 手写 Web 服务器(一)> 中介绍了 ...

  2. JavaSE 手写 Web 服务器(一)

    原文地址:JavaSE 手写 Web 服务器(一) 博客地址:http://www.extlight.com 一.背景 某日,在 Java 技术群中看到网友讨论 tomcat 容器相关内容,然后想到自 ...

  3. 黑马vue---40、结合Node手写JSONP服务器剖析JSONP原理

    黑马vue---40.结合Node手写JSONP服务器剖析JSONP原理 一.总结 一句话总结: 服务端可以返回js代码给script标签,那么标签会执行它,并且可带json字符串作为参数,这样就成功 ...

  4. 【项目】手写FTP服务器-C++实现FTP服务器

    X_FTP_server 手写FTP服务器-C++实现FTP服务器 项目Gitee链接:https://gitee.com/hsby/ftp_Server 简介 一个基于libevent的高并发FTP ...

  5. 手写Tomcat服务器

    预备知识 编写服务器用到的知识点 1) Socket 编程2) HTML3) HTTP 协议4) 反射5) XML 解析6) 服务器编写 Socket编程 https://www.cnblogs.co ...

  6. 手写Javaweb服务器

    简单web服务器 回忆socket 创建客服端(在httpClient_1包下) public class Client {    public static void main(String[] a ...

  7. 利用html 5 websocket做个山寨版web聊天室(手写C#服务器)

    在之前的博客中提到过看到html5 的websocket后很感兴趣,终于可以摆脱长轮询(websocket之前的实现方式可以看看Developer Works上的一篇文章,有简单提到,同时也说了web ...

  8. MiniCat:手写Http服务器

    minicat 项目介绍 已实现http基础协议.参数接受.servlet.filter.cookie.多文件上传等.支持NIO. 一款轻量化Http服务器.支持bio.nio两种模式.归属Coody ...

  9. 手写网站服务器~用Python手动实现一个简单的服务器,不借助任何框架在浏览器中输出任意内容

    写在前面的一些P话: 在公司网站开发中,我们往往借助于Flask.Django等网站开发框架去提高网站开发效率.那么在面试后端开发工程师的时候,面试官可能就会问到网站开发的底层原理是什么? 我们不止仅 ...

随机推荐

  1. js原生removeclass方法

    //如果列表中有存在给定的值就删除 // function removeClass(ele,txt){ // var str = ele.className, // ary = str.split(/ ...

  2. Why are very few schools involved in deep learning research? Why are they still hooked on to Bayesian methods?

    Why are very few schools involved in deep learning research? Why are they still hooked on to Bayesia ...

  3. httpsclient 自动获取证书 无证书访问 验证过能直接用

    首先实现写一个 实现接口SecureProtocolSocketFactory的类. /** *ClassName: bcde *date: 2015年2月26日 下午4:51:01 * *@auth ...

  4. DJANGO结合jQuery cxSelect 作二级菜单过滤

    EN,到这个阶段,基本功能算是完成了. 使用了jQuery cxSelect这个插件. http://code.ciaoca.com/jquery/cxselect/ 相关代码如下: html: &l ...

  5. codeforces #310 div1 D

    一开始写了个暴力模拟绳子的摆动轨迹 然后在Test 16 T掉了 后来%了一下别人的代码,发现需要对特殊情况进行特殊处理 首先我们考虑绳子的向右摆动,设当前位置为p,绳子当前长度为L 如果其旋转中心位 ...

  6. 看文档要看仔细,英语要加强啊... cocos2d-x 的 API 和 对应版本的 cocos2d-js 的 API 没有完全对应

    /** * Sets the X rotation (angle) of the node in degrees which performs a horizontal rotational skew ...

  7. Java Web开发 之JavaBean整理

    JavaBean是一种Java组件技术,就其本质就是一个类,具有如下特点:1:实现可序列化2:有一个public的无参的构造方法3:所有实例变量都是private的4:为每一个属性提供getter和s ...

  8. ajax跨域访问的解决方案

    今天的工作中要访问摄像机内部的一个web站点,这就涉及到jquery的ajax跨域访问的问题.我使用的是jquery1.7的版本,下面总结如下: 问题一:一开始用IE调试,总是返回No Transpo ...

  9. POJ2503——Babelfish(map映射+string字符串)

    Babelfish DescriptionYou have just moved from Waterloo to a big city. The people here speak an incom ...

  10. POJ1850——Code(组合数学)

    Code DescriptionTransmitting and memorizing information is a task that requires different coding sys ...