如何仅使用标准网络库发送HTTP响应? [英] How can I send an HTTP Response using only standard network libraries?
问题描述
我正在开发一个Web编程类的第一个家庭作业项目,即用Java编写一个简单的Web服务器。我正处于数据来回传输的地步,对于未经训练的眼睛,我的婴儿服务器似乎工作正常。但是,我找不到发送适当回复的方法。 (换句话说,无效页面请求将显示404-ish HTML页面,但在查看响应标头时仍会返回200 OK状态)。
I'm working on my first homework project in a web programming class, which is to write a simple web server in Java. I'm at the point where I have data being transmitted back and forth, and to the untrained eye, my baby server seems to be working fine. However, I can't find a way to send appropriate responses. (In other words, an invalid page request would show a 404-ish HTML page, but it still returns a 200 OK status when I view response headers).
我只能使用标准网络库进行套接字管理,而标准I / O库则可以从输入流中读取和写入字节和字符串。以下是一些相关的代码:
I'm limited to being able to use standard network libraries for socket management and standard I/O libraries to read and write bytes and strings from an input stream. Here's some pertinent code:
来自我的主...
ServerSocket servSocket = new ServerSocket(port, 10); // Bind the socket to the port
System.out.println("Opened port " + port + " successfully!");
while(true) {
//Accept the incoming socket, which means that the server process will
//wait until the client connects, then prepare to handle client commands
Socket newDataSocket = servSocket.accept();
System.out.println("Client socket created and connected to server socket...");
handleClient(newDataSocket); //Call handleClient method
}
来自handleClient方法...(在循环内解析请求方法和路径)
From the handleClient method...(inside a loop that parses the request method and path)
if(checkURL.compareTo("/status") == 0) { // Check to see if status page has been requested
System.out.println("STATUS PAGE"); // TEMPORARY. JUST TO MAKE SURE WE ARE PROPERLY ACCESSING STATUS PAGE
sendFile("/status.html", dataStream);
}
else {
sendFile(checkURL, dataStream); // If not status, just try the input as a file name
}
来自sendFile方法...
From sendFile method...
File f = new File(where); // Create the file object
if(f.exists() == true) { // Test if the file even exists so we can handle a 404 if not.
DataInputStream din;
try {
din = new DataInputStream(new FileInputStream(f));
int len = (int) f.length(); // Gets length of file in bytes
byte[] buf = new byte[len];
din.readFully(buf);
writer.write("HTTP/1.1 200 OK\r\n"); // Return status code for OK (200)
writer.write("Content-Length: " + len + "\r\n"); // WAS WRITING TO THE WRONG STREAM BEFORE!
writer.write("Content-Type: "+type+"\r\n\r\n\r\n"); // TODO VERIFY NEW CONTENT-TYPE CODE
out.write(buf); // Writes the FILE contents to the client
out.flush();
out.close();
} catch (FileNotFoundException e) {
e.printStackTrace(); // Not really handled since that's not part of project spec, strictly for debug.
}
}
else {
writer.write("HTTP/1.1 404 Not Found\r\n"); // Attempting to handle 404 as simple as possible.
writer.write("Content-Type: text/html\r\n\r\n\r\n");
sendFile("/404.html", sock);
}
任何人都能解释一下,在sendFile的条件下,我可以改变响应在404块中(就像我之前说过的,响应头仍然显示200 OK)?这是我的废话,我只是想使用HTTPResponse类,但我不能。 (另外,如果f.exists == true,则不显示内容长度和类型。)
Can anybody explain how, in the conditional from sendFile, I can change the response in the 404 block (Like I said before, the response headers still show 200 OK)? This is bugging the crap out of me, and I just want to use the HTTPResponse class but I can't. (Also, content length and type aren't displayed if f.exists == true.)
谢谢!
推荐答案
您看到的问题很可能与您的编写器上缺少
flush()
有关/ code>。根据您使用哪种类型的 Writer
,首先将字节写入需要刷新到流的缓冲区。这可以解释为什么输出中缺少 Content-Length
和 Content-Type
。只需在将其他数据写入流之前将其刷新。
The problem you are seeing is most likely related to a missing flush()
on your writer
. Depending on which type of Writer
you use the bytes are first written to a buffer that needs to be flushed to the stream. This would explain why Content-Length
and Content-Type
are missing in the output. Just flush it before you write additional data to the stream.
进一步调用 sendFile(/ 404.html,sock);
。你没有在这里发布完整的方法 - 但我想你在 sendFile
内递归调用它,因此发送 200 OK
文件状态 /404.html
。
Further you call sendFile("/404.html", sock);
. You did not post the full method here - but I suppose that you call it recursively inside sendFile
and thus send the 200 OK
status for your file /404.html
.
这篇关于如何仅使用标准网络库发送HTTP响应?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!