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