forked from aofeng/JavaTutorial
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHttpServerMock.java
More file actions
90 lines (76 loc) · 2.75 KB
/
HttpServerMock.java
File metadata and controls
90 lines (76 loc) · 2.75 KB
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
package cn.aofeng.demo.jetty;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.eclipse.jetty.server.Handler;
import org.eclipse.jetty.server.Request;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.handler.AbstractHandler;
/**
* HTTP服务器MOCK,可用于单元测试时模拟HTTP服务器的响应。
*
* @author <a href="mailto:aofengblog@163.com">聂勇</a>
*/
public class HttpServerMock {
public final static int DEFAULT_PORT = 9191;
public final static String DEFAULT_CONTENT_TYPE = "application/json";
public final static int DEFAULT_STATUS_CODE=HttpServletResponse.SC_OK;
private Server _httpServer;
private int _port;
public HttpServerMock() {
_port = DEFAULT_PORT;
}
public HttpServerMock(int port) {
_port = port;
}
/**
* 启动Jetty服务器。默认的响应status code为"200",content type为"application/json"。
* @param content 响应内容
*/
public void start(String content) throws Exception {
start(content, DEFAULT_CONTENT_TYPE, DEFAULT_STATUS_CODE);
}
/**
* 启动Jetty服务器。默认的响应status code为"200"。
* @param content 响应内容
* @param contentType 响应内容的MIME类型
*/
public void start(String content, String contentType) throws Exception {
start(content, contentType, DEFAULT_STATUS_CODE);
}
/**
* 启动Jetty服务器。
* @param content 响应内容
* @param contentType 响应内容的MIME类型
* @param statuCode 响应状态码
*/
public void start(String content, String contentType,
int statuCode) throws Exception {
_httpServer = new Server(_port);
_httpServer.setHandler(createHandler(content, contentType, statuCode));
_httpServer.start();
}
/**
* 停止Jetty服务器。
*/
public void stop() throws Exception {
if (null != _httpServer) {
_httpServer.stop();
_httpServer = null;
}
}
private Handler createHandler(final String content, final String contentType,
final int statusCode) {
return new AbstractHandler() {
@Override
public void handle(String target, Request baseRequest, HttpServletRequest request,
HttpServletResponse response) throws IOException, ServletException {
response.setContentType(contentType);
response.setStatus(statusCode);
baseRequest.setHandled(true);
response.getWriter().print(content);
}
};
}
}