1.http协议
超文本传输协议(HTTP-Hypertext transferprotocol)是一种详细规定了浏览器和
web服务器之间互相通信的规则,通过英特网传送万维网文档的数据传送协议。http协议
是一个应用层协议,是一个文本协议,由请求消息和响应消息构成,是一个标准的客户
端服务器模型。http是一个无状态的协议。用于服务器和客户机之间传输超文本文件
http的消息类 http的消息类型分为两大类。
请求消息(request):有客户端发给服务器的消息。其中组成包括:请求行(Request-Line),
可选的头部域(Header Field),及实体部分(Entity-Body)。
响应(response)消息:是服务端回复客户端请求的消息,其中组成包括状态行(Status-Line)
可选的头部(Header-Field),级实体(Entity-Body)
下面是我用发送消息的方法连接服务器,并得到服务器的响应。
首先在服务器写一个名为aa.jsp,放到tomact的root下面,
Enumeration names = request.getHeaderNames();
while(names.hasMoreElements()){
String name = (String)names.nextElement();
out.print(name+":"+request.getHeader(name)+"
");
System.out.println(name+":"+request.getHeader(name));
}
%>
编程实现连接
public class HttpTomact {
public static void main(String[] args) {
StringBuffer ab=new StringBuffer();
ab.append("GET /aa.jsp HTTP/1.1\r\n");//请求行
ab.append("Host:localhost:8080\r\n");
ab.append("Connection: close\r\n");//可选头部域
ab.append("\r\n");
//下面是用scoket发送请求和用io流输入、输出
Socket sb;
try {
sb = new Socket("localhost",8080);
OutputStream bos=sb.getOutputStream();
bos.write(ab.toString().getBytes());
InputStream is=sb.getInputStream();
BufferedReader br=new BufferedReader(new InputStreamReader(is),1024);
String line;
StringBuffer respContent=new StringBuffer();
while( (line=br.readLine())!=null )
{
respContent.append(line);
System.out.println(""+ line.length() +" " +line);
}
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
这是服务器输出的
返回的数据
证明是可以连接上的,上面是用get方法请求的,若要用post方法请求
只需换请求行方法,再在头部加数据类型,再加上body部分即可例如
ab.append("POST /index.jsp HTTP/1.1\r\n");
ab.append("Host:localhost:8080\r\n");
ab.append("Accept-Language:zh-cn\r\n");
ab.append("Content-Type: application/x-www-form-urlencoded\r\n");
ab.append("Connection: close\r\n");
ab.append("\r\n");
现在只是简单的连接上服务器,下一篇再分析如何处理请求和回传数据。