Http webserver数组越界错误

时间:2017-02-15 14:29:35

标签: java http

我一直在使用java中的简单HTTP Web服务器。但是我似乎遇到了一个问题,当我试图在请求中获取文件名时,我得到一个数组越界错误,即使它不超出界限,我可以清楚地看到它在数组中。任何人都可以帮助代码

public static void main(String[]args) throws Exception{
    ServerSocket ss = new ServerSocket(8080);

    while(true){
        Socket s= ss.accept();
        String ip = s.getInetAddress().toString();
        ConnectionHandler ch = new ConnectionHandler(s);
        ch.start();
        System.out.println(ip);

    }

public class ConnectionHandler extends Thread{

private Socket s;
private PrintWriter pw;
private BufferedReader br;

public ConnectionHandler(Socket s) throws Exception{
    this.s = s;
    br = new BufferedReader(new InputStreamReader(s.getInputStream()));
    pw = new PrintWriter(s.getOutputStream());
}

@Override
public void run(){
    String reqs = "";

    try {
        while(br.ready()){
            reqs += (char) br.read(); 
            //System.out.println(reqs);
            HttpRequest hr = new HttpRequest(reqs); 
            HttpResponse res = new HttpResponse(hr);
            pw.write(res.response.toCharArray());


        }
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    finally{
        pw.close();
        try {
            br.close();
            s.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }
}

}

public class HttpRequest {

 String fileName;

public HttpRequest(String reqs){

    String lines[] = reqs.split("\n");

    //System.out.println(lines[0]);
    String lines1[] = lines[0].split(" ");
    for(int i = 0;i<lines1.length;i++){
        System.out.println(i + lines1[i]);

    }
    fileName = lines1[1]; //error is here


}

}

public class HttpResponse {

private HttpRequest req;
String response;
private String root="H:/root";
private FileInputStream fis;
private File f;
public HttpResponse(HttpRequest hr) throws Exception {
    req = hr;
    if(req.fileName == null){
         f = new File("H:/root/helloworld.html");
         fis = new FileInputStream(f);
    }else{
         f = new File(root + req.fileName);
         fis = new FileInputStream(f);
    }


    response = "HTTP/1.1 200";
    response += "content-type: text/html \r\n";
    response += "Connection: close \r\n";
    response += "content-length: " + f.length() + "\r\n";
    response += "\r\n";
    int s;
    while((s=fis.read())!=-1){
        response += (char) s;
    }
    fis.close();
}

}

1 个答案:

答案 0 :(得分:0)

问题在于: reqs += (char) br.read(); 只读取输入中的单个字符,并在每个读取字符后尝试解析请求。

所以你最终会遇到一个情况,你的reqs中只有“G”会导致lines1的长度为1. lines1[1]会尝试访问该数组中的第二个元素,而不是存在。

尝试在循环之外移动请求的解析。

[编辑]答案中更好的格式支持。这对我有用。

while (br.ready())  {
    reqs += (char) br.read();
}
HttpRequest hr = new HttpRequest(reqs);
HttpResponse res = new HttpResponse(hr);
pw.write(res.response.toCharArray());