Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/http/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 编写一个简单的HTTP服务器来接受GET请求_Java_Http_Get - Fatal编程技术网

Java 编写一个简单的HTTP服务器来接受GET请求

Java 编写一个简单的HTTP服务器来接受GET请求,java,http,get,Java,Http,Get,我正在尝试创建一个简单的服务器来接受请求,然后将文件内容写入发送请求的浏览器。服务器连接并写入套接字。但是我的浏览器说 没有收到任何数据 没有显示任何内容 public class Main { /** * @param args */ public static void main(String[] args) throws IOException{ while(true){ ServerSocket serverSock = new ServerSocket(

我正在尝试创建一个简单的服务器来接受请求,然后将文件内容写入发送请求的浏览器。服务器连接并写入套接字。但是我的浏览器说

没有收到任何数据

没有显示任何内容

public class Main {

/**
 * @param args
 */
public static void main(String[] args) throws IOException{

    while(true){
        ServerSocket serverSock = new ServerSocket(6789);
        Socket sock = serverSock.accept();

        System.out.println("connected");

        InputStream sis = sock.getInputStream();
        BufferedReader br = new BufferedReader(new InputStreamReader(sis));
        String request = br.readLine(); // Now you get GET index.html HTTP/1.1`
        String[] requestParam = request.split(" ");
        String path = requestParam[1];

        System.out.println(path);

        PrintWriter out = new PrintWriter(sock.getOutputStream(), true);
        File file = new File(path);
        BufferedReader bfr = null;
        String s = "Hi";

        if (!file.exists() || !file.isFile()) {
            System.out.println("writing not found...");
             out.write("HTTP/1.0 200 OK\r\n");
             out.write(new Date() + "\r\n");
             out.write("Content-Type: text/html");
             out.write("Content length: " + s.length() + "\r\n");
             out.write(s);
        }else{
            FileReader fr = new FileReader(file);
            bfr = new BufferedReader(fr);
            String line;
            while ((line = bfr.readLine()) != null) {
                out.write(line);
            }
        }
        if(bfr != null){
            bfr.close();
        }
        br.close();
        out.close();
        serverSock.close();
    }
}

}
如果我使用,您的代码适用于我(数据显示在浏览器中)

http://localhost:6789/etc/hosts
还有一个文件
/etc/hosts
(Linux文件系统符号)


如果文件不存在,则此代码段

out.write(“HTTP/1.0 200正常\r\n”);
out.write(新日期()+“\r\n”);
out.write(“内容类型:text/html\r\n”);
out.write(“\r\n”);
out.write(“文件”+未找到文件+”\r\n);
out.flush();
将返回显示在浏览器中的数据:请注意,我在此处显式添加了对
flush()
的调用。确保在另一种情况下也刷新了
out

另一种可能是对
close
语句重新排序。 引用EJP对以下问题的回答:

您应该关闭从套接字创建的最外面的输出流。那会把它冲掉的

如果最外层的输出流是(来自同一源的另一个引用),则情况尤其如此:

一个缓冲的输出流,或者一个围绕一个输出流的流。如果你不关上它,它就不会被冲洗

因此,应该在
br.close()
之前调用
out.close()