以下是一个简单的Java HTTP服务器示例,可以通过浏览器访问并显示网页内容。
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
public class SimpleHttpServer {
public static void main(String[] args) {
try {
ServerSocket serverSocket = new ServerSocket(80);
while (true) {
Socket socket = serverSocket.accept();
handleRequest(socket);
}
} catch (IOException e) {
e.printStackTrace();
}
}
private static void handleRequest(Socket socket) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String line;
String requestMethod = null;
String requestUri = null;
while ((line = reader.readLine()) != null && !line.trim().isEmpty()) {
if (line.startsWith("GET")) {
String[] parts = line.split("\\s+");
requestMethod = parts[0];
requestUri = parts[1];
}
}
if (requestMethod == null || requestUri == null) {
return;
}
OutputStream outputStream = socket.getOutputStream();
PrintWriter writer = new PrintWriter(new OutputStreamWriter(outputStream));
if (requestUri.equals("/")) {
writer.println("HTTP/1.1 200 OK");
writer.println("Content-Type: text/html; charset=utf-8");
writer.println("Connection: close");
writer.println();
writer.println("<html><head><title>Welcome</title></head>");
writer.println("<body><h1>Welcome to my website!</h1></body></html>");
} else {
writer.println("HTTP/1.1 404 Not Found");
writer.println("Content-Type: text/plain; charset=utf-8");
writer.println("Connection: close");
writer.println();
writer.println("404 Not Found");
}
writer.flush();
reader.close();
writer.close();
socket.close();
}
}
该程序使用了Java的Socket类和ServerSocket类构建HTTP服务器,监听80端口。当浏览器发送GET请求时,服务器将解析请求中的方法和URI,根据请求URI返回相应的内容。
在以上代码中,当请求URI为"/"时,返回一个简单的欢迎页面;否则返回404 Not Found错误。可以通过修改输出内容及请求处理部分的代码来实现包含动态内容和更复杂功能的Web应用程序。
注意,此示例代码是一个仅用于演示HTTP服务器基本工作原理的简单程序,因此并未考虑实际应用中可能涉及的各种安全漏洞、性能问题等问题,请勿直接在生产环境中使用。
标签:HTTP,浏览器,socket,close,writer,访问,new,网页内容,println From: https://blog.51cto.com/u_16096459/6509127