实现一个简易的http模拟器

/**
* http模拟器
* 模拟发送http请求和接收http响应
*/

public class HttpSimulator
{
//主机
private String host = "localhost";
//端口
private int port = 80;
//是否为post请求方式
private boolean isPost;
//是否为head请求方式
private boolean isHead;
//记录从控制台输入的请求消息
private StringBuilder requestMessage = new StringBuilder();
private Socket socket;
//换行符
private static final String LINE_SEPARATOR = System.getProperty("line.separator");

public void run() throws IOException
{
BufferedReader consoleReader = new BufferedReader(new InputStreamReader(System.in));
try
{
while (true)
{
//解析host和port
if (!readRequestHostAndPort(consoleReader))
return;
//解析http request
readHttpRequest(consoleReader);
//发送http request
sendHttpRequest();
//读取http response
readHttpResponse(consoleReader);
}
}
finally
{
if (consoleReader != null)
{
try
{
consoleReader.close();
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
}

private boolean readRequestHostAndPort(BufferedReader consoleReader) throws IOException
{
System.out.print("host:port>");
String content = consoleReader.readLine();

if ("q".equals(content))
return false;

//解析host和port 如果没有输入 使用默认值
String[] parts = content.split(":");
String host_str = parts[0].trim();
if (host_str.length() > 0)
host = host_str;
if (parts.length > 1)
port = Integer.parseInt(parts[1].trim());
return true;
}

private void readHttpRequest(BufferedReader consoleReader) throws IOException
{
System.out.println("-----------------Request Header-----------------");
String content = consoleReader.readLine();

//解析请求行 获取请求方式 POST? HEAD?
requestMessage.append(content).append(LINE_SEPARATOR);
String[] parts = content.split(" +");
String method = parts[0].trim();
isPost = "POST".equals(method);
isHead = "HEAD".equals(method);

//读取控制台输入的请求头信息 当读到"" 结束循环
while (!"".equals(content = consoleReader.readLine()))
requestMessage.append(content).append(LINE_SEPARATOR);
requestMessage.append(LINE_SEPARATOR);

//如果是post请求 继续读取请求体内容
if (isPost)
{
while (!"".equals(content = consoleReader.readLine()))
requestMessage.append(content).append(LINE_SEPARATOR);
}
}

private void sendHttpRequest() throws IOException
{
socket = new Socket();
System.out.println("connecting " + host + ":" + port);
//设置read超时3000毫秒
socket.setSoTimeout(3000);
//设置连接超时5000毫秒
socket.connect(new InetSocketAddress(host, port), 5000);

//发送http请求
PrintWriter out = new PrintWriter(socket.getOutputStream());
out.println(requestMessage.toString());
out.flush();
socket.shutdownOutput();
//清空已经发送的http消息
requestMessage.delete(0, requestMessage.length());
}

private void readHttpResponse(BufferedReader consoleReader) throws IOException
{
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String line = null;
boolean headReaded = false;
System.out.println("-----------------Response Header-----------------");
try
{
//读取响应内容(状态行、响应头、响应体)
while (null != (line = in.readLine()))
{
//读到"" 表明响应头读取结束 headReaded赋值为true 且不是HEAD请求 处理响应消息
if ("".equals(line) && !headReaded && !isHead)
{
System.out.print("Show Data? ");
String confirm = consoleReader.readLine();
headReaded = true;
if ("Y".equals(confirm.toUpperCase()))
{
System.out.println("-----------------HTTP Response Data-----------------");
System.out.println(line);
continue;
}
else
break;
}
else
{
System.out.println(line);
}
}
}
finally
{
socket.close();
}
}

public static void main(String[] args) throws IOException
{
new HttpSimulator().run();
}
}



运行结果:
host:port>localhost:8080
-----------------Request Header-----------------
GET /test_web/test.html HTTP/1.1
Host:

connecting localhost:8080
-----------------Response Header-----------------
HTTP/1.1 200 OK
Server: Apache-Coyote/1.1
Accept-Ranges: bytes
ETag: W/"259-1397034177525"
Last-Modified: Wed, 09 Apr 2014 09:02:57 GMT
Content-Type: text/html
Content-Length: 259
Date: Tue, 15 Apr 2014 07:22:38 GMT
Show Data? y
-----------------HTTP Response Data-----------------

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
哈哈
</body>
</html>
host:port>
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值