客户请求的浏览器类型

<td width="50%"><%=request.getHeader("User-Agent")%> </td>
<td height="4">客户请求的浏览器类型</td>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是伪代码实现这个功能: ```java import java.io.*; import java.net.*; public class HttpServer { private static final String HTTP_VERSION = "HTTP/1.1"; private static final String SERVER_NAME = "MyHTTPServer/1.0"; public static void main(String[] args) throws IOException { ServerSocket serverSocket = new ServerSocket(80); // 创建服务器套接字,监听80端口 System.out.println("Server started"); while (true) { Socket clientSocket = serverSocket.accept(); // 等待客户端连接 // 从连接套接字接收 HTTP 请求 BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream())); String requestLine = in.readLine(); System.out.println("Received request: " + requestLine); // 解释 HTTP 请求,获取请求的文件名 String fileName = parseFileName(requestLine); // 从服务器的文件系统获取请求的文件 File file = new File(fileName); if (!file.exists()) { // 如果文件不存在,返回 "404 Not Found" 响应 send404Response(clientSocket); } else { // 创建 HTTP 响应报文并发送给客户端 sendFileResponse(clientSocket, file); } clientSocket.close(); // 关闭连接套接字 } } private static String parseFileName(String requestLine) { // 解析 HTTP 请求,获取请求的文件名 // 假设请求行的格式为 "GET /index.html HTTP/1.1" String[] parts = requestLine.split(" "); String fileName = parts[1]; return fileName; } private static void send404Response(Socket clientSocket) throws IOException { String response = HTTP_VERSION + " 404 Not Found\r\n" + "Server: " + SERVER_NAME + "\r\n" + "Content-Type: text/html\r\n" + "\r\n" + "<html><body><h1>404 Not Found</h1></body></html>"; OutputStream out = clientSocket.getOutputStream(); out.write(response.getBytes()); out.flush(); } private static void sendFileResponse(Socket clientSocket, File file) throws IOException { // 创建 HTTP 响应报文,包括首部行和文件内容 String contentType = getContentType(file); String response = HTTP_VERSION + " 200 OK\r\n" + "Server: " + SERVER_NAME + "\r\n" + "Content-Type: " + contentType + "\r\n" + "\r\n"; OutputStream out = clientSocket.getOutputStream(); out.write(response.getBytes()); // 发送文件内容 FileInputStream fileIn = new FileInputStream(file); byte[] buffer = new byte[1024]; int bytesRead; while ((bytesRead = fileIn.read(buffer)) != -1) { out.write(buffer, 0, bytesRead); } fileIn.close(); out.flush(); } private static String getContentType(File file) { // 根据文件后缀名返回 MIME 类型 String fileName = file.getName(); if (fileName.endsWith(".html") || fileName.endsWith(".htm")) { return "text/html"; } else if (fileName.endsWith(".jpg") || fileName.endsWith(".jpeg")) { return "image/jpeg"; } else if (fileName.endsWith(".gif")) { return "image/gif"; } else { return "application/octet-stream"; } } } ``` 需要注意的是,这只是一个简单的 HTTP 服务器的伪代码实现,实际上还有很多细节和安全性方面的考虑。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值