Java客户端-服务端程序如何在浏览器展示HTTP 200 OK等响应内容
具体修改方案
1. 修复正常响应头缺失问题
你当前正常请求的响应逻辑只输出了Content-Type和Content-Length,缺少HTTP协议要求的状态行和连接控制头,直接修改sendResponseHeader方法如下:
private static void sendResponseHeader(String type,int length) { // 输出HTTP状态行 out.print("HTTP/1.1 200 OK\r\n"); // 输出连接关闭标识 out.print("Connection: close\r\n"); out.print("Content-Type: " + type + "\r\n"); out.print("Content-Length: " + length + "\r\n"); // HTTP协议要求头部结束后必须加一个空行分隔头部和响应体 out.print("\r\n"); out.flush(); }
2. 修正错误响应的格式问题
你现有的错误响应存在换行不规范、状态行无换行、内容类型和返回内容不匹配的问题,修改sendErrorResponse方法如下:
private static void sendErrorResponse(int errorCode) { switch(errorCode) { case 404: out.print("HTTP/1.1 404 Not Found\r\n"); out.print("Connection: close\r\n"); // 404返回HTML内容,类型要对应改为text/html out.print("Content-Type: text/html\r\n"); out.print("\r\n"); out.println("<html><head><title>Error</title></head><body> <h2>Error: 404 Not Found</h2> <p>你请求的资源在当前服务器上不存在。</p> </body></html>"); break; case 501: out.print("HTTP/1.1 501 Not Implemented\r\n"); out.print("Connection: close\r\n"); out.print("Content-Type: text/plain\r\n"); out.print("\r\n"); out.println("当前服务器不支持该请求方法"); break; } out.flush(); }
3. 额外优化建议
- 避免使用static类型的
out变量,多线程并发请求时会出现输出内容错乱的问题,建议将输出流作为参数传递给相关响应方法 - 读取请求头时增加null判断,避免客户端异常断开时
readLine返回null触发空指针异常 - 拼接文件路径时增加路径校验,过滤
../之类的特殊字符,防止攻击者通过路径穿越漏洞读取服务器上的其他敏感文件
内容的提问来源于stack exchange,提问作者Hynisel
相关产品推荐
相关产品推荐

