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