簡體   English   中英

Java Socket如何處理包含多個參數的GET請求?

[英]How to handle GET request that contains multiple parameters Java Socket?

我正在編寫一個服務器,它將使用 Java 套接字編程接受 GET 請求。 首先我創建一個 ServerSocket 對象。

 ServerSocket serverSocket = new ServerSocket(portNumber);
    System.out.println("Server listening on port " + portNumber);

    // Listen for incoming connections and handle them in a separate thread
    while (true) {
        // Accept an incoming connection
        Socket clientSocket = serverSocket.accept();

        // Create a new thread to handle the request
        Thread thread = new Thread(new ClientHandler(clientSocket,roomNames));
        thread.start();
    }

在 ClientHandler(實現 Runnable 類)內部,我得到這樣的輸入和輸出流:

  @Override
public void run() {
    try {
        // Get the input and output streams for the socket
        BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));


        PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
        String request;
        // Read the incoming request
        request= in.readLine();

        //Print the request to the console
        System.out.println("request is:  "+request);
        // Parse the request to extract the query string
        String[] requestParts = request.split(" ");
        String url = requestParts[1];
        //print the url to the console
        System.out.println("url is:  "+url);
        String queryString = ""; // continues...}

當我在命令行中使用 cURL 發出請求時,這就是我得到的:

在此處輸入圖像描述

這是服務器的控制台輸出:

在此處輸入圖像描述

我想要實現的是獲取 URL 中的參數並使用它們添加到數組列表中。 正如您在后一張圖片中看到的那樣,請求是“ GET /reserve?name=Z2115 HTTP/1.1 ”。 我只能獲取名稱參數的值,而不能獲取日期、小時和持續時間。

正如@Stephen C 在評論中指出的那樣,我需要在卷曲的開頭和結尾添加“(引號)。它起作用了。 在此處輸入圖像描述

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM