weixin_43536432 2020-02-21 08:14 采纳率: 0%
浏览 267

301重定向抛出空指针异常。

尝试添加301重定向,出现socket的inpustream变成null抛出空指针异常

            in = new BufferedReader(new InputStreamReader(connect.getInputStream()));

怀疑可能因为用了单thread的问题,但不知道怎么解决

Thread thread = new Thread(myServer);
                thread.start();

以下为完整代码


import java.io.BufferedOutputStream;
import java.io.*;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.*;
import java.util.Date;
import java.util.StringTokenizer;

// The tutorial can be found just here on the SSaurel's Blog : 
// https://www.ssaurel.com/blog/create-a-simple-http-web-server-in-java
// Each Client Connection will be managed in a dedicated Thread
public class http2_server implements Runnable{ 

    static final File WEB_ROOT = new File(".");
    static final String DEFAULT_FILE = "index.html";
    static final String FILE_NOT_FOUND = "404.html";
    static final String METHOD_NOT_SUPPORTED = "not_supported.html";
    // port to listen connection
    static final int PORT = 8080;

    // verbose mode
    static final boolean verbose = true;

    // Client Connection via Socket Class
    private Socket connect;

    public http2_server(Socket c) {
        connect = c;
    }

    public static void main(String[] args) {
        try {
            ServerSocket serverConnect = new ServerSocket(PORT);
            System.out.println("Server started.\nListening for connections on port : " + PORT + " ...\n");

            // we listen until user halts server execution
            while (true) {
                http2_server myServer = new http2_server(serverConnect.accept());

                if (verbose) {
                    System.out.println("Connecton opened. (" + new Date() + ")");
                }

                // create dedicated thread to manage the client connection
                Thread thread = new Thread(myServer);
                thread.start();
            }

        } catch (IOException e) {
            System.err.println("Server Connection error : " + e.getMessage());
        }
    }

    @Override
    public void run() {
        // we manage our particular client connection
        BufferedReader in = null; PrintWriter out = null; BufferedOutputStream dataOut = null;
        String fileRequested = null;

        try {
            // we read characters from the client via input stream on the socket
            in = new BufferedReader(new InputStreamReader(connect.getInputStream()));
            // we get character output stream to client (for headers)
            out = new PrintWriter(connect.getOutputStream());
            // get binary output stream to client (for requested data)
            dataOut = new BufferedOutputStream(connect.getOutputStream());

            // get first line of the request from the client
            String input = in.readLine();
            // we parse the request with a string tokenizer
            StringTokenizer parse = new StringTokenizer(input);
            String method = parse.nextToken().toUpperCase(); // we get the HTTP method of the client
            // we get file requested
            fileRequested = parse.nextToken().toLowerCase();


                // GET or HEAD method
                if (fileRequested.endsWith("/")) {
                    fileRequested += DEFAULT_FILE;
                }

                File file = new File(WEB_ROOT, fileRequested);
                int fileLength = (int) file.length();
                String content = getContentType(fileRequested);

                if (method.equals("GET")) { // GET method so we return content
                    if(!fileRequested.endsWith(".html")){
                        fileRequested = fileRequested.substring(1, fileRequested.length());

                        if(fileRequested.equals("abc")) {
                            out.println("HTTP/1.1 200 OK");
                            out.println("Content-type: text/html;charset=utf-8");
                            out.println("Content-length: 10");
                            out.println(); // blank line between headers and content, very important !

                            out.println("<h1>hellow!!!</h1>");
                            out.flush(); // flush character output stream buffer
                        }else{
                            if(fileRequested.trim().equals("312")) {
                                out.println("HTTP/1.1 301 Moved Permanently");
                                out.println("Location: http://localhost:8080/abc");

                                out.flush();
                                }else {

                                out.println("HTTP/1.1 404 File Not Found");
                                out.println("Server: Java HTTP Server from SSaurel : 1.0");
                                out.println("Date: " + new Date());
                                out.println("Content-type:text/html ");
                                out.println("Content-length:20");
                                out.println(); // blank line between headers and content, very important !
                                out.println("<h1>404 NOT FOUND</h1>");

                                out.flush();
                                }
                            } 
                    }else {


                    byte[] fileData = readFileData(file, fileLength);

                    // send HTTP Headers
                    out.println("HTTP/1.1 200 OK");
                    out.println("Server: Java HTTP Server from SSaurel : 1.0");
                    out.println("Date: " + new Date());
                    out.println("Content-type: " + content);
                    out.println("Content-length: " + fileLength);
                    out.println(); // blank line between headers and content, very important !
                    out.flush(); // flush character output stream buffer

                    dataOut.write(fileData, 0, fileLength);
                    dataOut.flush();
                }
                }
                if (verbose) {
                    System.out.println("File " + fileRequested + " of type " + content + " returned");
                }



        } catch (FileNotFoundException fnfe) {
            try {
                fileNotFound(out);
            } catch (IOException ioe) {
                System.err.println("Error with file not found exception : " + ioe.getMessage());
            }

        } catch (IOException ioe) {
            System.err.println("Server error : " + ioe);
        } finally {
            try {
                in.close();
                out.close();
                dataOut.close();
                connect.close(); // we close socket connection
            } catch (Exception e) {
                System.err.println("Error closing stream : " + e.getMessage());
            } 

            if (verbose) {
                System.out.println("Connection closed.\n");
            }
        }


    }

    private byte[] readFileData(File file, int fileLength) throws IOException {
        FileInputStream fileIn = null;
        byte[] fileData = new byte[fileLength];

        try {
            fileIn = new FileInputStream(file);
            fileIn.read(fileData);
        } finally {
            if (fileIn != null) 
                fileIn.close();
        }

        return fileData;
    }

    // return supported MIME Types
    private String getContentType(String fileRequested) {
        if (fileRequested.endsWith(".htm")  ||  fileRequested.endsWith(".html"))
            return "text/html";
        else
            return "text/plain";
    }

    private void fileNotFound(PrintWriter out) throws IOException {


        out.println("HTTP/1.1 404 File Not Found");
        out.println("Server: Java HTTP Server from SSaurel : 1.0");
        out.println("Date: " + new Date());
        out.println("Content-type:text/html ");
        out.println("Content-length:20 ");
        out.println(); // blank line between headers and content, very important !
        out.println("<h1>404 NOT FOUND</h1>");

        out.flush(); // flush character output stream buffer


    }

}
  • 写回答

1条回答 默认 最新

  • lshen01 2023-03-17 08:58
    关注

    参考GPT和自己的思路:

    根据您提供的信息,空指针异常发生在以下代码行:

    in = new BufferedReader(new InputStreamReader(connect.getInputStream()));
    

    这是因为当您使用301重定向时,connect 可能是空值。这可能是由于您在单个线程中处理多个客户端连接时导致的问题。

    为了解决这个问题,您可以将每个客户端连接移动到单独的线程中进行处理。在 main 函数中,您已经为每个连接创建了一个新线程,但是,在 run 函数中,您需要将所有读取字节流和输出字节流的操作放入 try-catch 块中,这样,您就可以在遇到异常时正确地关闭和释放相关资源。

    例如:

    @Override
    public void run() {
        // we manage our particular client connection
        BufferedReader in = null; 
        PrintWriter out = null; 
        BufferedOutputStream dataOut = null;
        String fileRequested = null;
    
        try {
            // we read characters from the client via input stream on the socket
            in = new BufferedReader(new InputStreamReader(connect.getInputStream()));
            // we get character output stream to client (for headers)
            out = new PrintWriter(connect.getOutputStream());
            // get binary output stream to client (for requested data)
            dataOut = new BufferedOutputStream(connect.getOutputStream());
    
            // other code here to handle the request
    
        } catch (IOException e) {
            System.err.println("Server error : " + e);
        } finally {
            try {
                in.close();
                out.close();
                dataOut.close();
                connect.close(); // we close socket connection
            } catch (Exception e) {
                System.err.println("Error closing stream : " + e.getMessage());
            } 
    
            if (verbose) {
                System.out.println("Connection closed.\n");
            }
        }
    }
    

    将每个客户端连接放入单独的线程中处理,有助于避免资源冲突和竞争。

    评论

报告相同问题?

悬赏问题

  • ¥15 怀疑手机被监控,请问怎么解决和防止
  • ¥15 Qt下使用tcp获取数据的详细操作
  • ¥15 idea右下角设置编码是灰色的
  • ¥15 全志H618ROM新增分区
  • ¥15 在grasshopper里DrawViewportWires更改预览后,禁用电池仍然显示
  • ¥15 NAO机器人的录音程序保存问题
  • ¥15 C#读写EXCEL文件,不同编译
  • ¥15 MapReduce结果输出到HBase,一直连接不上MySQL
  • ¥15 扩散模型sd.webui使用时报错“Nonetype”
  • ¥15 stm32流水灯+呼吸灯+外部中断按键