import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
public class HttpServer {
public static void main(String[] args) {
try {
// 启动 HTTP 服务器端口监听
ServerSocket serverSocket = new ServerSocket(80);
while (true) {
// 等待客户端连接到服务,客户端连接后返回一个新的socket
Socket server = serverSocket.accept();
// 获取网络的输入流,并将其转换为带有缓冲器的字符流
InputStream inputStream = server.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String requestHeaders;
int contentLength = 0;
// 客户端的请求格式
while ((null != (requestHeaders = bufferedReader.readLine()))&& !requestHeaders.isEmpty()){
// 显示浏览器的请求头信息
System.out.println(requestHeaders);
if (requestHeaders.startsWith("GET")){
int begin = requestHeaders.indexOf(" ");
int end = requestHeaders.indexOf("HTTP");
String condition = requestHeaders.substring(begin, end);
System.out.println("GET 请求参数:" + condition);
}
if (requestHeaders.startsWith("Content-Length")){
int begin = requestHeaders.indexOf("Content-Length:") + "Content-Length:".length();
String postParameterLength = requestHeaders.substring(begin).trim();
contentLength = Integer.parseInt(postParameterLength);
System.out.println("Post 请求的参数的长度是:" + contentLength);
}
}
StringBuffer buffer = new StringBuffer();
if (contentLength > 0){
}
OutputStream outputStream = server.getOutputStream();
PrintWriter printWriter = new PrintWriter(outputStream);
// 服务器的响应格式
printWriter.println("HTTP/1.1 200 OK");
printWriter.println("Content-Type: text/html;charset=utf-8");
printWriter.println();
printWriter.println("<h1>访问 HTTP 服务器 成功!</h1>");
printWriter.flush();
server.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
|