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