Java 如何实现一个http服务器
【摘要】 在Java中可以使用HttpServer类来实现Http服务器,该类位于com.sun.net包下(rt.jar)。实现代码如下:主程序类12345678910111213141516171819202122package bg.httpserver; import com.sun.net.httpserver.HttpServer;import java.io.IOException;im...
在Java中可以使用HttpServer类来实现Http服务器,该类位于com.sun.net包下(rt.jar)。实现代码如下:
主程序类
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
|
package bg.httpserver;
import com.sun.net.httpserver.HttpServer;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.util.concurrent.Executors;
public class HttpServerStarter {
public static void main(String[] args) throws IOException {
//创建一个HttpServer实例,并绑定到指定的IP地址和端口号
HttpServer httpServer = HttpServer.create( new InetSocketAddress( 8080 ), 0 );
//创建一个HttpContext,将路径为/myserver请求映射到MyHttpHandler处理器
httpServer.createContext( "/myserver" , new MyHttpHandler());
//设置服务器的线程池对象
httpServer.setExecutor(Executors.newFixedThreadPool( 10 ));
//启动服务器
httpServer.start();
}
}
|
HttpServer:HttpServer主要是通过带参的create方法来创建,第一个参数InetSocketAddress表示绑定的ip地址和端口号。第二个参数为int类型,表示允许排队的最大TCP连接数,如果该值小于或等于零,则使用系统默认值。
createContext:可以调用多次,表示将指定的url路径绑定到指定的HttpHandler处理器对象上,服务器接收到的所有路径请求都将通过调用给定的处理程序对象来处理。
setExecutor:设置服务器的线程池对象,不设置或者设为null则表示使用start方法创建的线程。
HttpHandler实现
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
|
package bg.httpserver;
import com.sun.net.httpserver.Headers;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
/**
* 处理/myserver路径请求的处理器类
*/
public class MyHttpHandler implements HttpHandler {
@Override
public void handle(HttpExchange httpExchange) {
try {
StringBuilder responseText = new StringBuilder();
responseText.append( "请求方法:" ).append(httpExchange.getRequestMethod()).append( "<br/>" );
responseText.append( "请求参数:" ).append(getRequestParam(httpExchange)).append( "<br/>" );
responseText.append( "请求头:<br/>" ).append(getRequestHeader(httpExchange));
handleResponse(httpExchange, responseText.toString());
} catch (Exception ex) {
ex.printStackTrace();
}
}
/**
* 获取请求头
* @param httpExchange
* @return
*/
private String getRequestHeader(HttpExchange httpExchange) {
Headers headers = httpExchange.getRequestHeaders();
return headers.entrySet().stream()
.map((Map.Entry<String, List<String>> entry) -> entry.getKey() + ":" + entry.getValue().toString())
.collect(Collectors.joining( "<br/>" ));
}
/**
* 获取请求参数
* @param httpExchange
* @return
* @throws Exception
*/
private String getRequestParam(HttpExchange httpExchange) throws Exception {
String paramStr = "" ;
if (httpExchange.getRequestMethod().equals( "GET" )) {
//GET请求读queryString
paramStr = httpExchange.getRequestURI().getQuery();
} else {
//非GET请求读请求体
BufferedReader bufferedReader = new BufferedReader( new InputStreamReader(httpExchange.getRequestBody(), "utf-8" ));
StringBuilder requestBodyContent = new StringBuilder();
String line = null ;
while ((line = bufferedReader.readLine()) != null ) {
requestBodyContent.append(line);
}
paramStr = requestBodyContent.toString();
}
return paramStr;
}
/**
* 处理响应
* @param httpExchange
* @param responsetext
* @throws Exception
*/
private void handleResponse(HttpExchange httpExchange, String responsetext) throws Exception {
//生成html
StringBuilder responseContent = new StringBuilder();
responseContent.append( "<html>" )
.append( "<body>" )
.append(responsetext)
.append( "</body>" )
.append( "</html>" );
String responseContentStr = responseContent.toString();
byte [] responseContentByte = responseContentStr.getBytes( "utf-8" );
//设置响应头,必须在sendResponseHeaders方法之前设置!
httpExchange.getResponseHeaders().add( "Content-Type:" , "text/html;charset=utf-8" );
//设置响应码和响应体长度,必须在getResponseBody方法之前调用!
httpExchange.sendResponseHeaders( 200 , responseContentByte.length);
OutputStream out = httpExchange.getResponseBody();
out.write(responseContentByte);
out.flush();
out.close();
}
}
|
运行HttpServerStarter,在浏览器中访问如下:
【版权声明】本文为华为云社区用户原创内容,转载时必须标注文章的来源(华为云社区)、文章链接、文章作者等基本信息, 否则作者和本社区有权追究责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱:
cloudbbs@huaweicloud.com
- 点赞
- 收藏
- 关注作者
评论(0)