下面的代码片断创建一个与本地HTTP服务器(127.0.0.1代表本地主机的IP地址)通信的
Socket,发送一个HTTP请求包,准备接收服务器的应答。
sb.append("GET /index.jsp HTTP/1.1\r\n");//注意\r\n为回车换行
sb.append("Accept-Language: zh-cn\r\n");
sb.append("Connection: Keep-Alive\r\n");
sb.append("Host: 192.168.0.106\r\n");
sb.append("Content-Length: 37\r\n");
sb.append("\r\n");
sb.append("userName=new_andy&password=new_andy\r\n");
sb.append("\r\n");
//向Web服务器发送一个HTTP请求包
os.write(sb.toString().getBytes());
服务器端的代码在大致结构为:
while (!shutdown) {
try {
socket = serverSocket.accept(); //等待客户以送HTTP请求包
// 创建HTTP请求包处理线程
RequestThread request = new RequestThread(socket);
request.start();
}
e.printStackTrace();
}
}
RequestThread线程分析HTTP请求包,跟根据请求包内容在服务端生成一个HTTP应答包。下一节说明怎样分析HTTP包。
InputStream input
= socket.
getInputStream(); //从此字节数据流获得HTTP请求包内容
OutputStream output
= socket.
getOutputStream(); //向此字节流写入HTTP应答包内容
三、读取HTTP包
以下我自己设计的一个读取HTTP包的类SocketRequest。
public class SocketRequest { //从指定的Socket的InputStream中读取数据
private int CONTENT_LENGTH=0; //实际包内容数据长
private boolean bePost = false;
private boolean beHttpResponse = false;
private boolean beChucked = false;
private boolean beGet = false;
private byte crlf13 = (byte)13; //碶 ?br/> private byte crlf10 = (byte)10; //碶 ?/FONT>
this.input = input;
}
public SocketRequest
(Socket socket
) {
this.input = socket.getInputStream();
}
public void ReadData() { //解析 获得InputStream的数据
ReadHeader(); //头部
if(beChucked) //为Chucked
{
int ChuckSize=0;
while((ChuckSize=getChuckSize())>0) //多个Chucked
{
readLenData(ChuckSize+2);//读取定长数据
}
readLenData(2); //最后的2位
}
if(CONTENT_LENGTH>0)
{
readLenData(CONTENT_LENGTH);//读取定长数据
}
uri = "";//parseUri(new String(request));
}
private void readLenData(int size) //读取定长数据
{
int readed=0; //已经读取数
try{
int available=0;//input.available(); //可读数
if(available>(size-readed)) available=size-readed;
while( readed<size )
{
while(available==0){ //等到有数据可读
available = input.available(); //可读数
}
if(available>(size-readed)) available= size-readed; //size-readed--剩余数
if(available>2048) available= 2048; //size-readed--剩余数
byte[] buffer = new byte[available];
int reading = input.read(buffer);
request
=request.
append(new String(buffer,
0,reading
)); //byte数组相加
readed+=reading; //已读字符
}
System.
out.
println("Read readLenData Error!");
}
}
private void ReadHeader() //读取头部 并获得大小
{
byte[] crlf = new byte[1];
int crlfNum= 0; //已经连接的回车换行数 crlfNum=4为头部结束
try{
while( input.read(crlf)!=-1 ) //读取头部
{
if(crlf[0]==crlf13 || crlf[0]==crlf10)
{
crlfNum++;
}
else
{ crlfNum=0; } //不是则清
request
=request.
append(new String(crlf,
0,
1)); //byte数组相加
if(crlfNum==4) break;
}
System.
out.
println("Read Http Header Error!");
return;
}
//这里我只处理了GET与POST方法
String strMethod
= tempStr.
substring(0,
4);
if(strMethod.equals("GET ")) //前
{ beGet=true;
}
else if(strMethod.equals("POST"))
{
bePost=true;
getContentlen_Chucked(tempStr);
}
else {
System.
out.
println("不支持的HTTP包类型");
} //其它的其它类型 暂不支持
}
private void getContentlen_Chucked
(String tempStr
) //获得长度 CONTENT-LENGTH 或 是否为CHUNKED型
{
int clIndex = tempStr.indexOf(ss1);
int chuckIndex = tempStr.indexOf(ss2); //为CHUNKED型
byte requst[]= tempStr.getBytes();
if(clIndex!=-1)
{ //从clIndex+1起至\r\n
for(int i=(clIndex+16);;i++)
{
if(requst[i]!=(byte)13 && requst[i]!=(byte)10 )
{
sb.append((char)requst[i]);
}
else
break;
}
CONTENT_LENGTH
=Integer.
parseInt(sb.
toString()); //正式的HTML文件的大小
//System.out.println("CONTENT_LENGTH== "+CONTENT_LENGTH);
}
if(chuckIndex!=-1) beChucked=true;
}
private int getChuckSize() //Chuck大小
{
byte[] crlf = new byte[1];
int crlfNum= 0; //已经连接的回车换行数 crlfNum=4为头部结束
try{
while(input.read(crlf)!=-1) //读取头部
{
if(crlf[0]==crlf13 || crlf[0]==crlf10)
{ crlfNum++; }
else
{ crlfNum=0; } //不是则清
sb1.append((char)crlf[0]);
request
=request.
append(new String(crlf,
0,
1)); //byte数组相加
if(crlfNum==2) break;
}
System.
out.
println("Read Http Package Error!");
return 0;
}
return Integer.
parseInt((sb1.
toString()).
trim(),
16); //16进控制
}
//通过此来进行过滤,是否为发至目标服务器的HTTP包
int index1, index2;
index1 = requestString.indexOf(??;
if (index1 != -1) {
index2 = requestString.indexOf(?? index1 + 1);
if (index2 > index1)
return requestString.substring(index1 + 1, index2);
}
return null;
}
return request.toString();
}
}
使用此类:
SocketRequest request = new SocketRequest(socket); //socket为ServerSocket.accept()返回的Socket实例
request.ReadData(); //读取数据
request.getData();
为什么我要用这么大的力量去读取呢,尤其是在因为
Socket连接在发送数据时,由于网络的原因经常会发生延迟现象,可能在服务器端开始接收数据时可能只有部分数据可以从
InputStream中获得,在一些地方处理不当时,可能只能获得不完整的数据或是错误的数据。
常用int read()与int read(byte[] b)。在用read(byte[])时,程序员经常会犯错误,因为在网络环境中,读取的数据量不一定等于参数的大小。
希望我的这篇文章能给你带来一些帮助。//源代码片段来自云代码http://yuncode.net