模擬介面請求到web伺服器

露水上的青蛙發表於2017-09-21

客戶端

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>

 

相關文章