在 Java 中建立 HTTP 代理伺服器

Sheeraz Gul 2023年10月12日
在 Java 中建立 HTTP 代理伺服器

在當今世界,代理幾乎是每個人的需要。本教程演示如何在 Java 中建立 HTTP 代理伺服器。

在 Java 中建立 HTTP 代理伺服器

代理伺服器是客戶端和伺服器之間的中間方法。本教程將演示一種在 Java 中建立 HTTP 代理伺服器的方法。

代理伺服器有一些優點,包括:

  1. 使用代理伺服器,我們可以建立有關流量的統計資訊。
  2. 使用代理伺服器,我們可以更新客戶端的內容。
  3. 我們可以用代理伺服器分析故障網路系統的反應。
  4. 我們可以使用代理伺服器來控制下載和上傳的限制。
  5. 我們可以使用代理伺服器來捕獲伺服器和客戶端之間的流量。

Java 支援不同協議的代理處理程式,例如 HTTP、FTP、HTTPS 等。ProxyHost 和 ProxyPort 用於 Java 中的 HTTP 代理伺服器。

讓我們嘗試在 Java 中實現一個 HTTP 代理伺服器:

package delftstack;

import java.io.*;
import java.net.*;
public class Proxy_Server {
  public static void main(String[] args) throws IOException {
    try {
      String Proxy_Host = "Our Proxy Server";
      int Remote_Port = 1025;
      int Local_Port = 1026;
      // Printing the start-up message
      System.out.println(
          "Starting proxy for " + Proxy_Host + ":" + Remote_Port + " on port " + Local_Port);
      // start the server
      Run_Server(Proxy_Host, Remote_Port, Local_Port);
    } catch (Exception e) {
      System.err.println(e);
    }
  }

  public static void Run_Server(String Proxy_Host, int Remote_Port, int Local_Port)
      throws IOException {
    // Create a ServerSocket to listen connections
    ServerSocket Server_Socket = new ServerSocket(Local_Port);
    final byte[] Request = new byte[1024];
    byte[] Reply = new byte[4096];
    while (true) {
      Socket Socket_Client = null, Socket_Server = null;
      try {
        // wait for a connection on the local port
        Socket_Client = Server_Socket.accept();
        final InputStream InputStreamClient = Socket_Client.getInputStream();
        final OutputStream OutputStreamClient = Socket_Client.getOutputStream();

        // Create the connection to the real server.
        try {
          Socket_Server = new Socket(Proxy_Host, Remote_Port);
        } catch (IOException e) {
          PrintWriter out = new PrintWriter(OutputStreamClient);
          out.print("The Proxy Server could not connect to " + Proxy_Host + ":" + Remote_Port
              + ":\n" + e + "\n");
          out.flush();
          Socket_Client.close();
          continue;
        }

        final InputStream InputStreamServer = Socket_Server.getInputStream();
        final OutputStream OutputStreamServer = Socket_Server.getOutputStream();

        // The thread to read the client's requests and to pass them
        Thread New_Thread = new Thread() {
          public void run() {
            int Bytes_Read;
            try {
              while ((Bytes_Read = InputStreamClient.read(Request)) != -1) {
                OutputStreamServer.write(Request, 0, Bytes_Read);
                OutputStreamServer.flush();
              }
            } catch (IOException e) {
            }

            // Close the connections
            try {
              OutputStreamServer.close();
            } catch (IOException e) {
            }
          }
        };

        // client-to-server request thread
        New_Thread.start();
        // Read server's responses and pass them to the client.
        int Bytes_Read;
        try {
          while ((Bytes_Read = InputStreamServer.read(Reply)) != -1) {
            OutputStreamClient.write(Reply, 0, Bytes_Read);
            OutputStreamClient.flush();
          }
        } catch (IOException e) {
        }
        // Close the connection
        OutputStreamClient.close();
      } catch (IOException e) {
        System.err.println(e);
      } finally {
        try {
          if (Socket_Server != null)
            Socket_Server.close();
          if (Socket_Client != null)
            Socket_Client.close();
        } catch (IOException e) {
        }
      }
    }
  }
}

上面的程式碼用 Java 實現了一個 HTTP 代理伺服器。連線成功的輸出是:

Starting proxy for Our Proxy Server:1025 on port 1026
作者: Sheeraz Gul
Sheeraz Gul avatar Sheeraz Gul avatar

Sheeraz is a Doctorate fellow in Computer Science at Northwestern Polytechnical University, Xian, China. He has 7 years of Software Development experience in AI, Web, Database, and Desktop technologies. He writes tutorials in Java, PHP, Python, GoLang, R, etc., to help beginners learn the field of Computer Science.

LinkedIn Facebook