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 package org.apache.http.client.fluent;
28
29 import java.io.File;
30 import java.io.FileOutputStream;
31 import java.io.IOException;
32 import java.io.InputStream;
33
34 import org.apache.http.HttpEntity;
35 import org.apache.http.HttpResponse;
36 import org.apache.http.StatusLine;
37 import org.apache.http.client.ClientProtocolException;
38 import org.apache.http.client.HttpResponseException;
39 import org.apache.http.client.ResponseHandler;
40 import org.apache.http.entity.ByteArrayEntity;
41 import org.apache.http.entity.ContentType;
42 import org.apache.http.util.EntityUtils;
43
44 public class Response {
45
46 private final HttpResponse response;
47 private boolean consumed;
48
49 Response(final HttpResponse response) {
50 super();
51 this.response = response;
52 }
53
54 private void assertNotConsumed() {
55 if (this.consumed) {
56 throw new IllegalStateException("Response content has been already consumed");
57 }
58 }
59
60 private void dispose() {
61 if (this.consumed) {
62 return;
63 }
64 try {
65 final HttpEntity entity = this.response.getEntity();
66 final InputStream content = entity.getContent();
67 if (content != null) {
68 content.close();
69 }
70 } catch (final Exception ignore) {
71 } finally {
72 this.consumed = true;
73 }
74 }
75
76
77
78
79 public void discardContent() {
80 dispose();
81 }
82
83
84
85
86 public <T> T handleResponse(
87 final ResponseHandler<T> handler) throws ClientProtocolException, IOException {
88 assertNotConsumed();
89 try {
90 return handler.handleResponse(this.response);
91 } finally {
92 dispose();
93 }
94 }
95
96 public Content returnContent() throws ClientProtocolException, IOException {
97 return handleResponse(new ContentResponseHandler());
98 }
99
100 public HttpResponse returnResponse() throws IOException {
101 assertNotConsumed();
102 try {
103 final HttpEntity entity = this.response.getEntity();
104 if (entity != null) {
105 final ByteArrayEntity byteArrayEntity = new ByteArrayEntity(
106 EntityUtils.toByteArray(entity));
107 final ContentType contentType = ContentType.getOrDefault(entity);
108 byteArrayEntity.setContentType(contentType.toString());
109 this.response.setEntity(byteArrayEntity);
110 }
111 return this.response;
112 } finally {
113 this.consumed = true;
114 }
115 }
116
117 public void saveContent(final File file) throws IOException {
118 assertNotConsumed();
119 final StatusLine statusLine = response.getStatusLine();
120 if (statusLine.getStatusCode() >= 300) {
121 throw new HttpResponseException(statusLine.getStatusCode(),
122 statusLine.getReasonPhrase());
123 }
124 final FileOutputStream out = new FileOutputStream(file);
125 try {
126 final HttpEntity entity = this.response.getEntity();
127 if (entity != null) {
128 entity.writeTo(out);
129 }
130 } finally {
131 this.consumed = true;
132 out.close();
133 }
134 }
135
136 }