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.Constructor;
32 import java.lang.reflect.InvocationHandler;
33 import java.lang.reflect.InvocationTargetException;
34 import java.lang.reflect.Method;
35 import java.lang.reflect.Proxy;
36
37 import org.apache.http.HttpEntity;
38 import org.apache.http.HttpResponse;
39 import org.apache.http.client.methods.CloseableHttpResponse;
40 import org.apache.http.util.EntityUtils;
41
42
43
44
45 @Deprecated
46 class CloseableHttpResponseProxy implements InvocationHandler {
47
48 private final static Constructor<?> CONSTRUCTOR;
49
50 static {
51 try {
52 CONSTRUCTOR = Proxy.getProxyClass(CloseableHttpResponseProxy.class.getClassLoader(),
53 new Class<?>[] { CloseableHttpResponse.class }).getConstructor(new Class[] { InvocationHandler.class });
54 } catch (final NoSuchMethodException ex) {
55 throw new IllegalStateException(ex);
56 }
57 }
58
59 private final HttpResponse original;
60
61 CloseableHttpResponseProxy(final HttpResponse original) {
62 super();
63 this.original = original;
64 }
65
66 public void close() throws IOException {
67 final HttpEntity entity = this.original.getEntity();
68 EntityUtils.consume(entity);
69 }
70
71 @Override
72 public Object invoke(
73 final Object proxy, final Method method, final Object[] args) throws Throwable {
74 final String mname = method.getName();
75 if (mname.equals("close")) {
76 close();
77 return null;
78 } else {
79 try {
80 return method.invoke(original, args);
81 } catch (final InvocationTargetException ex) {
82 final Throwable cause = ex.getCause();
83 if (cause != null) {
84 throw cause;
85 } else {
86 throw ex;
87 }
88 }
89 }
90 }
91
92 public static CloseableHttpResponse newProxy(final HttpResponse original) {
93 try {
94 return (CloseableHttpResponse) CONSTRUCTOR.newInstance(new CloseableHttpResponseProxy(original));
95 } catch (final InstantiationException ex) {
96 throw new IllegalStateException(ex);
97 } catch (final InvocationTargetException ex) {
98 throw new IllegalStateException(ex);
99 } catch (final IllegalAccessException ex) {
100 throw new IllegalStateException(ex);
101 }
102 }
103
104 }