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 package org.apache.hc.client5.testing.classic;
29
30 import java.io.IOException;
31 import java.util.Locale;
32
33 import org.apache.hc.core5.http.ClassicHttpRequest;
34 import org.apache.hc.core5.http.ClassicHttpResponse;
35 import org.apache.hc.core5.http.ContentType;
36 import org.apache.hc.core5.http.HttpEntity;
37 import org.apache.hc.core5.http.HttpException;
38 import org.apache.hc.core5.http.HttpStatus;
39 import org.apache.hc.core5.http.MethodNotSupportedException;
40 import org.apache.hc.core5.http.io.HttpRequestHandler;
41 import org.apache.hc.core5.http.io.entity.ByteArrayEntity;
42 import org.apache.hc.core5.http.io.entity.EntityUtils;
43 import org.apache.hc.core5.http.protocol.HttpContext;
44
45
46
47
48 public class EchoHandler implements HttpRequestHandler {
49
50
51
52
53
54
55
56
57
58
59
60
61 @Override
62 public void handle(final ClassicHttpRequest request,
63 final ClassicHttpResponse response,
64 final HttpContext context)
65 throws HttpException, IOException {
66
67 final String method = request.getMethod().toUpperCase(Locale.ROOT);
68 if (!"GET".equals(method) &&
69 !"HEAD".equals(method) &&
70 !"POST".equals(method) &&
71 !"PUT".equals(method)) {
72 throw new MethodNotSupportedException(method + " not supported by " + getClass().getName());
73 }
74
75 HttpEntity entity = request.getEntity();
76
77
78
79 final byte[] data;
80 final ContentType contentType;
81 if (entity == null) {
82 data = new byte [0];
83 contentType = null;
84 } else {
85 data = EntityUtils.toByteArray(entity);
86 final String contentTypeStr = entity.getContentType();
87 contentType = contentTypeStr == null ? null : ContentType.parse(contentTypeStr);
88 }
89
90 entity = new ByteArrayEntity(data, contentType);
91
92 response.setCode(HttpStatus.SC_OK);
93 response.setEntity(entity);
94 }
95
96 }