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.impl.client;
29
30 import java.io.IOException;
31 import java.lang.reflect.InvocationHandler;
32 import java.lang.reflect.InvocationTargetException;
33 import java.lang.reflect.Method;
34 import java.lang.reflect.Proxy;
35
36 import org.apache.http.HttpEntity;
37 import org.apache.http.HttpResponse;
38 import org.apache.http.annotation.NotThreadSafe;
39 import org.apache.http.client.methods.CloseableHttpResponse;
40 import org.apache.http.util.EntityUtils;
41
42
43
44
45 @NotThreadSafe
46 class CloseableHttpResponseProxy implements InvocationHandler {
47
48 private final HttpResponse original;
49
50 CloseableHttpResponseProxy(final HttpResponse original) {
51 super();
52 this.original = original;
53 }
54
55 public void close() throws IOException {
56 final HttpEntity entity = this.original.getEntity();
57 EntityUtils.consume(entity);
58 }
59
60 public Object invoke(
61 final Object proxy, final Method method, final Object[] args) throws Throwable {
62 final String mname = method.getName();
63 if (mname.equals("close")) {
64 close();
65 return null;
66 } else {
67 try {
68 return method.invoke(original, args);
69 } catch (final InvocationTargetException ex) {
70 final Throwable cause = ex.getCause();
71 if (cause != null) {
72 throw cause;
73 } else {
74 throw ex;
75 }
76 }
77 }
78 }
79
80 public static CloseableHttpResponse newProxy(final HttpResponse original) {
81 return (CloseableHttpResponse) Proxy.newProxyInstance(
82 CloseableHttpResponseProxy.class.getClassLoader(),
83 new Class<?>[] { CloseableHttpResponse.class },
84 new CloseableHttpResponseProxy(original));
85 }
86
87 }