многопоточный http-сервер для получения GET и POST из клиентского браузера - PullRequest
0 голосов
/ 16 марта 2012

Я пытаюсь запустить простой многопоточный сервер, который выбирает URL, а также позволяет браузеру загружать файл на сервер (GET и POST), он выбирает веб-страницу с помощью GET. У меня проблемы с POST, вот мой WebServerЯ использую для загрузки работы.Примечание: HttpRequest - это еще один класс, который обрабатывает потоки

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


public class WebServer
{

    public WebServer(int port)
    {

        System.out.println("starting web server on port " + port);

        ServerSocket serverSocket = null;

        try
        {
            //create the server
            serverSocket = new ServerSocket(port);
        }catch(IOException ex)
        {
            System.out.println("could not open port " + port);
            System.exit(1);
        }

        //loop indefinitely
        while(true)
        {
            try
            {
                Socket connection = null;
                connection = serverSocket.accept();
                //accept the connection

                //create a new thread, start it and return to the waiting state
                HttpRequest request = new HttpRequest(connection);
                Thread t = new Thread(request);
                t.start();

            }catch(IOException ex)
            {
                //fail if an error occurs
                System.out.println("problem accepting connection");
                System.exit(1);
            }
        }

    }

    public static void main(String[] args)
    {

        //simple validation for the port number
        if(args.length != 1)
        {
            System.out.println("please specify a port");
            System.exit(1);
        }

        int port = -1;
        try
        {
            port = Integer.parseInt(args[0]);

        }catch(NumberFormatException ex)
        {
            System.out.println("invalid port number");
            System.exit(1);
        }

        WebServer server = new WebServer (port);

    }

}

, здесь Http реализует работоспособный

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

public class HttpRequest implements Runnable
{

    private DataInputStream input = null;
    private Socket connection;

    private static DataOutputStream output = null;

    public HttpRequest(Socket connection)
    {
        this.connection = connection;
    }

    //required method so this can be used as a thread
    public void run()
    {
        try
        {
            //try and get the streams
            input = new DataInputStream(connection.getInputStream());
            output = new DataOutputStream(connection.getOutputStream());
        }
        catch(IOException ex)
        {
            System.out.println("could not get input/output streams from connection: " + connection.toString());
            return;
        }

        try
        {
            StringBuilder response = new StringBuilder("");

            String request = input.readLine();

            System.out.println("request: " + request);

            String[] requestArray = request.split(" ");

            //read off and ignore the rest of the input
            //added so this can be tested with real browsers
            while(input.available() != 0)
            {
                input.read();
            }

            if (requestArray.length != 3)
            {
                //request should be of the format GET /index.html HTTP/1.1, die if a bad request comes in
                System.out.println("bad request: " + request);
                return;
            }else
            {
                //requested file should be the second entry, remove the leading '/'
                File requestedFile = new File(requestArray[1].substring(1));

                System.out.println("requested file: " + requestedFile);

                //check the requested file exists
                if(requestedFile.exists())
                {
                    System.out.println("file found, sending response");

                    DataInputStream fileInput = new DataInputStream(new FileInputStream(requestedFile));

                    //output HTTP header, must be followed by two new lines
                    response.append("HTTP/1.1 200 OK\n\n");

                    String line = fileInput.readLine();

                    while(line != null)
                    {
                        response.append(line);
                        line = fileInput.readLine();
                    }

                    fileInput.close();

                    output.writeBytes(response.toString());
                    output.flush();
                    output.close();

                    Logger.writeToLog("Request: " + request + "\r\nResponse: " + response.toString());

                }
                else
                {
                    System.out.println("file not found, sending 404");

                    response.append("HTTP/1.1 404 Not Found\n\n");
                    output.writeBytes(response.toString());

                    output.flush();
                    output.close();
                }

            }

        }
        catch(IOException ex)
        {
            System.out.println("cannot read request from: " + connection.toString() + ex.toString());
            return;
        }
        catch(NullPointerException ex)
        {
            System.out.println("bad request: " + connection.toString());
            return;
        }

        try
        {
            input.close();
            output.close();

            connection.close();
        }
        catch(IOException ex)
        {
            System.out.println("Can't close connection: " + connection.toString());
            return;
        }
    }

}

1 Ответ

2 голосов
/ 16 марта 2012

Ваша проблема в том, что ваш класс HttpRequest неправильно реализует протокол HTTP. Для начала вы предполагаете, что все запросы являются запросами GET, и игнорируете строки заголовка, следующие за строкой запроса.

Что вам нужно сделать, это прочитать спецификацию HTTP 1.1 ... полностью ... и переписать ваш код так, чтобы он читал и обрабатывал запросы, а также генерировал ответы в соответствии с тем, как спецификация говорит, что это должно быть сделано.

В качестве альтернативы, не тратьте свое время на переизобретение колеса (вероятно, неправильно). Используйте существующую структуру веб-контейнера или существующий стек протоколов HTTP, например Apache HttpComponents.

...