模拟界面请求到web服务器

客户端

package com.lsw.client;

import java.io.*;
import java.net.*;
import java.util.*;

public class HTTPClinet {
    public static void main(String[] args){
        //确定http请求的uri
        String uri = "index.html";
        if(args.length !=0)
            uri = args[0];
        
        //按照get请求方式访问httpserver
        doGet("localhost",8080,uri);    
    }
    //按照get请求方式访问httpserver
    public static void doGet(String host,int port,String uri){
        Socket socket = null;
        
        try{
            //与httpserver建立ftp连接
            socket = new Socket(host,port);
        }
        catch(Exception e){
            e.printStackTrace();
        }
        
        try{
            //创建http请求
            //http请求的第一行
            StringBuffer sb = new StringBuffer("GET "+uri+" HTTP/1.1\r\n");
            //http请求头
            sb.append("Accept: */*\r\n");
            sb.append("Accept-Language: zh-cn\r\n");
            sb.append("Accept-Encoding: gzip, deflate\r\n");
            sb.append("User-Agent: HTTPClient\r\n");
            sb.append("Host: localhost:8080\r\n");
            sb.append("Connection: Keep-Alive\r\n\r\n");
            
            //发送http请求
            OutputStream socketOut = socket.getOutputStream(); //获得输出流
            socketOut.write(sb.toString().getBytes());
            
            //睡眠2秒,等待响应结果
            Thread.sleep(2000);
            
            //接收响应结果
            InputStream socketIn = socket.getInputStream(); //获得输入流
            int size = socketIn.available();
            byte[] buffer = new byte[size];
            socketIn.read(buffer);
            String request = new String(buffer);
            System.out.println(request);
        }
        catch(Exception e){
            e.printStackTrace();
        }
        finally{
            try{
                socket.close();
            }catch(Exception e){
                e.printStackTrace();
            }
        }
    }

}

服务端

package com.lsw.server;

import java.io.*;
import java.net.*;

public class HTTPServer {
    public static void main(String[] args){
        int port;
        ServerSocket serverSocket;
        
        try{
            port = Integer.parseInt(args[0]);
            System.out.println("默认端口是: " + port);
        }
        catch(Exception e){
            System.out.println("默认端口8080");
            port = 8080;
        }
        
        try{
            //创建监听端口
            serverSocket = new ServerSocket(port);
            System.out.println("服务器正在监听端口: " + serverSocket.getLocalPort());
            while(true){
                try{
                    //等待客户的链接请求
                    final Socket socket = serverSocket.accept();
                    System.out.println("建立了一个与客户的新的TCP连接,该客户的地址为: " + socket.getInetAddress()
                            + " 端口为 : " + socket.getPort());
                    //响应客户请求
                    service(socket);
                }
                catch(Exception e){
                    e.printStackTrace();
                }
            }   
            
        }
        catch(Exception e){
            e.printStackTrace();
        }
    }
    
    public static void service(Socket socket) throws Exception{
        //读取HTTP请求信息
        InputStream socketIn = socket.getInputStream(); //获得输入流
        //睡眠500毫秒,等待http请求
        Thread.sleep(500);
        int size = socketIn.available();
        byte[] buffer = new byte[size];
        socketIn.read(buffer);
        String request = new String(buffer);
        //打印http请求数据
        System.out.println("客户端请求的数据为: " +request);
        
        //解析http请求
        //获得http请求第一行
        String firstLineOfRequest = request.substring(0,request.indexOf("\r\n"));
        System.out.println("firstLineOfRequest= " +firstLineOfRequest);
        //解析http请求的第一行
        String[] parts = firstLineOfRequest.split(" ");
        //解析http请求这种的uri
        String uri = parts[1];
        System.out.println("解析http请求这种的uri=" + uri);
        System.out.println("截图的值为=" + uri.substring(0, 1).toString());
        String flag = uri.substring(0, 1).toString();
        if(flag.equals("/")){
            System.out.println("此请求是从浏览器发起的请求");
            uri = uri.substring(1).toString();
        }
           
        System.out.println("解析http请求这种的uri=" + uri);
        
        //决定http响应正文的类型,此处作了简化处理
        String contentType;
        if(uri.indexOf("html") != -1 || uri.indexOf("htm") != -1)
            contentType ="text/html";
        else if(uri.indexOf("jpg") != -1 || uri.indexOf("jpeg") != -1)
            contentType ="image/jpeg";
        else if(uri.indexOf("gif") != -1)
            contentType ="image/gif";
        else
            contentType = "application/octet-stream"; //字节流类型
        
        //创建http响应结果
        //创建http响应的第一行
        String responseFirstLine = "HTTP/1.1 200 OK\r\n";
        //http响应头
        String responseHeader = "Content-Type:" +contentType + "\r\n\r\n";
        //获得读取响应正文数据的输入流
        /*InputStream in = HTTPServer.class.getResourceAsStream(uri); 书上这么写的  哎*/
        InputStream in = HTTPServer.class.getClassLoader().getResourceAsStream(uri);
        
        //发送http响应结果
        OutputStream socketOut = socket.getOutputStream(); //获得输出流
        //发送http响应的第一行
        socketOut.write(responseFirstLine.getBytes());
        //发送http响应的头
        socketOut.write(responseHeader.getBytes());
        System.out.println("报文头发送完成");
        System.out.println("开始发送http响应的正文");
        //发送http响应的正文
        int len = 0;
        buffer = new byte[1024];
        try {
            while((len=in.read(buffer)) != -1)
                socketOut.write(buffer, 0, len);
            
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println("完成发送http响应的正文");
        //睡眠1秒,等待客户接收http响应结果
        Thread.sleep(1000);
        //关闭tcp连接
        socket.close();
        
    }

}
<!DOCTYPE html>
<html>
  <head>
    <title>hello.html</title>
    
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="this is my page">
    <meta http-equiv="content-type" content="text/html; charset=UTF-8">
    
    <!--<link rel="stylesheet" type="text/css" href="./styles.css">-->

  </head>
  
  <body>
    This is my HTML page. <br>
  </body>
</html>

 

posted @ 2017-09-21 22:30  露水上的青蛙  阅读(293)  评论(0编辑  收藏  举报