Java 浏览器请求与web服务器应答

来源:互联网 发布:段子 知乎 编辑:程序博客网 时间:2024/06/03 02:32

HTML:
浏览器向web服务器请求网页,使用tcp协议,向其发送特定格式的数据字段,web服务器根据这些字段中携带的信息作出对应的应答。
浏览器请求字段:

GET /myweb/1.html  HTTP/1.1   // 请求行  请求方式  /myweb/1.html  请求的资源路径   http协议版本。 /*请求消息头 . 属性名:属性值*/Accept: image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/x-shockwave-flash, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, */* // 其中*/*表示所有的文件类型Accept-Language: zh-cn,zu;q=0.5Accept-Encoding: gzip, deflateUser-Agent: Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; InfoPath.2)Host: 192.168.1.100:9090//Host: www.huyouni.com:9090Connection: Keep-Alive//空行//请求体

WEB服务器应答:

HTTP/1.1 200 OK   //应答行,http的协议版本   应答状态码   应答状态描述信息Server: Apache-Coyote/1.1ETag: W/"199-1323480176984"Last-Modified: Sat, 10 Dec 2011 01:22:56 GMTContent-Type: text/htmlContent-Length: 199Date: Fri, 11 May 2012 07:51:39 GMTConnection: close//空行//应答体,网页源码

实例:模拟浏览器与web服务器代码
浏览器端:

Socket s = new Socket("192.168.1.100",8080);PrintWriter out = new PrintWriter(s.getOutputStream(),true);out.println("GET /myweb/1.html HTTP/1.1");out.println("Accept: */*");out.println("Host: 192.168.1.100:8080");out.println("Connection: close");out.println();//空行out.println();InputStream in = s.getInputStream();byte[] buf = new byte[1024];int len = in.read(buf);String str =new String(buf,0,len);System.out.println(str);s.close();

服务器端:

ServerSocket ss = new ServerSocket(9090);        Socket s = ss.accept();        System.out.println(s.getInetAddress().getHostAddress()+".....connected");        InputStream in = s.getInputStream();            byte[] buf = new byte[1024];            int len = in.read(buf);        String text = new String(buf,0,len);        System.out.println(text);           PrintWriter out = new PrintWriter(s.getOutputStream(),true);        out.println("<font color='red' size='7'>欢迎光临</font>");//返回网页源码        s.close();    ss.close();

Java将URL封装,直接提供访问服务,不需要如上的人工发送请求字段

String str_url = "http://192.168.1.100:8080/myweb/1.html";        URL url = new URL(str_url);//      获取信息,更多信息见API文档                                                    //System.out.println("getProtocol:"+url.getProtocol());//      System.out.println("getHost:"+url.getHost());//      System.out.println("getPort:"+url.getPort());//      System.out.println("getFile:"+url.getFile());//      System.out.println("getPath:"+url.getPath());//      System.out.println("getQuery:"+url.getQuery());        InputStream in = url.openStream();//该句等于下面两句        URLConnection conn = url.openConnection();        InputStream in = conn.getInputStream();//      String value = conn.getHeaderField("Content-Type");//获取服务器端的信息(文件类型等等)        byte[] buf = new byte[1024];        int len = in.read(buf);        String text = new String(buf,0,len);        System.out.println(text);        in.close();
0 0
原创粉丝点击