0
# Response Handling
1
2
Apache HttpClient provides flexible response processing capabilities including handler interfaces, closeable responses for proper resource management, and utility methods for content extraction and status code handling.
3
4
## Response Interfaces
5
6
### HttpResponse
7
8
```java { .api }
9
public interface HttpResponse extends HttpMessage {
10
StatusLine getStatusLine();
11
void setStatusLine(StatusLine statusline);
12
void setStatusLine(ProtocolVersion ver, int code);
13
void setStatusLine(ProtocolVersion ver, int code, String reason);
14
void setStatusCode(int code);
15
void setReasonPhrase(String reason);
16
HttpEntity getEntity();
17
void setEntity(HttpEntity entity);
18
Locale getLocale();
19
void setLocale(Locale loc);
20
}
21
```
22
23
Base interface for HTTP responses containing status line, headers, and entity.
24
25
### CloseableHttpResponse
26
27
```java { .api }
28
public interface CloseableHttpResponse extends HttpResponse, Closeable {
29
void close() throws IOException;
30
}
31
```
32
33
HTTP response that implements Closeable for proper resource management.
34
35
```java
36
try (CloseableHttpResponse response = httpClient.execute(httpGet)) {
37
StatusLine statusLine = response.getStatusLine();
38
int statusCode = statusLine.getStatusCode();
39
40
if (statusCode == 200) {
41
HttpEntity entity = response.getEntity();
42
String responseBody = EntityUtils.toString(entity);
43
System.out.println(responseBody);
44
}
45
}
46
```
47
48
## Response Handlers
49
50
### ResponseHandler Interface
51
52
```java { .api }
53
public interface ResponseHandler<T> {
54
T handleResponse(HttpResponse response) throws ClientProtocolException, IOException;
55
}
56
```
57
58
Strategy interface for processing HTTP responses and converting them to desired types.
59
60
### Basic Response Handler
61
62
```java
63
ResponseHandler<String> responseHandler = new ResponseHandler<String>() {
64
@Override
65
public String handleResponse(HttpResponse response) throws IOException {
66
int status = response.getStatusLine().getStatusCode();
67
if (status >= 200 && status < 300) {
68
HttpEntity entity = response.getEntity();
69
return entity != null ? EntityUtils.toString(entity) : null;
70
} else {
71
throw new ClientProtocolException("Unexpected response status: " + status);
72
}
73
}
74
};
75
76
String responseBody = httpClient.execute(httpGet, responseHandler);
77
```
78
79
### JSON Response Handler Example
80
81
```java
82
ResponseHandler<JsonObject> jsonHandler = new ResponseHandler<JsonObject>() {
83
@Override
84
public JsonObject handleResponse(HttpResponse response) throws IOException {
85
int status = response.getStatusLine().getStatusCode();
86
if (status >= 200 && status < 300) {
87
HttpEntity entity = response.getEntity();
88
if (entity != null) {
89
String json = EntityUtils.toString(entity);
90
return JsonParser.parseString(json).getAsJsonObject();
91
}
92
}
93
throw new ClientProtocolException("Unexpected response status: " + status);
94
}
95
};
96
97
JsonObject jsonResponse = httpClient.execute(httpGet, jsonHandler);
98
```
99
100
## Status Line Processing
101
102
### StatusLine Interface
103
104
```java { .api }
105
public interface StatusLine {
106
ProtocolVersion getProtocolVersion();
107
int getStatusCode();
108
String getReasonPhrase();
109
}
110
```
111
112
Interface representing the HTTP response status line.
113
114
```java
115
CloseableHttpResponse response = httpClient.execute(httpGet);
116
StatusLine statusLine = response.getStatusLine();
117
int statusCode = statusLine.getStatusCode();
118
String reasonPhrase = statusLine.getReasonPhrase();
119
ProtocolVersion protocolVersion = statusLine.getProtocolVersion();
120
121
System.out.println("Status: " + statusCode + " " + reasonPhrase);
122
System.out.println("Protocol: " + protocolVersion);
123
```
124
125
## Entity Processing
126
127
### HttpEntity Interface
128
129
```java { .api }
130
public interface HttpEntity {
131
boolean isRepeatable();
132
boolean isChunked();
133
long getContentLength();
134
Header getContentType();
135
Header getContentEncoding();
136
InputStream getContent() throws IOException, UnsupportedOperationException;
137
void writeTo(OutputStream outstream) throws IOException;
138
boolean isStreaming();
139
void consumeContent() throws IOException;
140
}
141
```
142
143
Interface representing HTTP message entity (request or response body).
144
145
### EntityUtils
146
147
```java { .api }
148
public final class EntityUtils {
149
public static void consume(HttpEntity entity) throws IOException;
150
public static void consumeQuietly(HttpEntity entity);
151
public static String toString(HttpEntity entity) throws IOException, ParseException;
152
public static String toString(HttpEntity entity, String defaultCharset) throws IOException, ParseException;
153
public static String toString(HttpEntity entity, Charset defaultCharset) throws IOException, ParseException;
154
public static byte[] toByteArray(HttpEntity entity) throws IOException;
155
public static void updateEntity(HttpResponse response, HttpEntity entity) throws IOException;
156
}
157
```
158
159
Utility methods for working with HTTP entities.
160
161
```java
162
try (CloseableHttpResponse response = httpClient.execute(httpGet)) {
163
HttpEntity entity = response.getEntity();
164
165
// Convert to string
166
String responseBody = EntityUtils.toString(entity);
167
168
// Convert to byte array
169
byte[] responseBytes = EntityUtils.toByteArray(entity);
170
171
// Get content length
172
long contentLength = entity.getContentLength();
173
174
// Check if repeatable
175
boolean repeatable = entity.isRepeatable();
176
177
// Consume entity to free resources
178
EntityUtils.consume(entity);
179
}
180
```
181
182
## Content Type Handling
183
184
### ContentType
185
186
```java { .api }
187
public final class ContentType {
188
public static final ContentType APPLICATION_ATOM_XML;
189
public static final ContentType APPLICATION_FORM_URLENCODED;
190
public static final ContentType APPLICATION_JSON;
191
public static final ContentType APPLICATION_OCTET_STREAM;
192
public static final ContentType APPLICATION_SVG_XML;
193
public static final ContentType APPLICATION_XHTML_XML;
194
public static final ContentType APPLICATION_XML;
195
public static final ContentType MULTIPART_FORM_DATA;
196
public static final ContentType TEXT_HTML;
197
public static final ContentType TEXT_PLAIN;
198
public static final ContentType TEXT_XML;
199
public static final ContentType WILDCARD;
200
201
public static ContentType create(String mimeType);
202
public static ContentType create(String mimeType, Charset charset);
203
public static ContentType create(String mimeType, String charset);
204
public static ContentType parse(String s) throws ParseException, UnsupportedCharsetException;
205
public static ContentType get(HttpEntity entity) throws ParseException, UnsupportedCharsetException;
206
public static ContentType getOrDefault(HttpEntity entity) throws ParseException, UnsupportedCharsetException;
207
208
public String getMimeType();
209
public Charset getCharset();
210
public String getParameter(String name);
211
}
212
```
213
214
Utility class for handling HTTP content types.
215
216
```java
217
try (CloseableHttpResponse response = httpClient.execute(httpGet)) {
218
HttpEntity entity = response.getEntity();
219
ContentType contentType = ContentType.get(entity);
220
221
if (contentType != null) {
222
String mimeType = contentType.getMimeType();
223
Charset charset = contentType.getCharset();
224
225
if (ContentType.APPLICATION_JSON.getMimeType().equals(mimeType)) {
226
String json = EntityUtils.toString(entity, charset);
227
// Process JSON response
228
}
229
}
230
}
231
```
232
233
## Header Processing
234
235
### Header Interface
236
237
```java { .api }
238
public interface Header {
239
String getName();
240
String getValue();
241
HeaderElement[] getElements() throws ParseException;
242
}
243
```
244
245
Interface representing an HTTP header.
246
247
### Working with Response Headers
248
249
```java
250
try (CloseableHttpResponse response = httpClient.execute(httpGet)) {
251
// Get all headers
252
Header[] allHeaders = response.getAllHeaders();
253
254
// Get specific header
255
Header contentType = response.getFirstHeader("Content-Type");
256
if (contentType != null) {
257
System.out.println("Content-Type: " + contentType.getValue());
258
}
259
260
// Get multiple headers with same name
261
Header[] setCookieHeaders = response.getHeaders("Set-Cookie");
262
for (Header header : setCookieHeaders) {
263
System.out.println("Set-Cookie: " + header.getValue());
264
}
265
266
// Check if header exists
267
boolean hasLocation = response.containsHeader("Location");
268
}
269
```
270
271
## Error Handling
272
273
### Exception Handling
274
275
```java { .api }
276
public class HttpResponseException extends ClientProtocolException {
277
public HttpResponseException(int statusCode, String reasonPhrase);
278
public int getStatusCode();
279
public String getReasonPhrase();
280
}
281
```
282
283
Exception thrown for HTTP error responses.
284
285
### Complete Error Handling Example
286
287
```java
288
try (CloseableHttpResponse response = httpClient.execute(httpGet)) {
289
StatusLine statusLine = response.getStatusLine();
290
int statusCode = statusLine.getStatusCode();
291
292
if (statusCode >= 200 && statusCode < 300) {
293
// Success - process response
294
HttpEntity entity = response.getEntity();
295
String responseBody = EntityUtils.toString(entity);
296
return responseBody;
297
298
} else if (statusCode >= 400 && statusCode < 500) {
299
// Client error
300
throw new ClientProtocolException("Client error: " + statusCode + " " + statusLine.getReasonPhrase());
301
302
} else if (statusCode >= 500) {
303
// Server error
304
throw new ClientProtocolException("Server error: " + statusCode + " " + statusLine.getReasonPhrase());
305
306
} else {
307
// Unexpected status
308
throw new ClientProtocolException("Unexpected status: " + statusCode);
309
}
310
311
} catch (IOException e) {
312
// Handle IO exceptions
313
throw new RuntimeException("Request failed", e);
314
}
315
```
316
317
## Streaming Response Processing
318
319
### Processing Large Responses
320
321
```java
322
try (CloseableHttpResponse response = httpClient.execute(httpGet)) {
323
HttpEntity entity = response.getEntity();
324
325
if (entity != null) {
326
try (InputStream inputStream = entity.getContent();
327
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8))) {
328
329
String line;
330
while ((line = reader.readLine()) != null) {
331
// Process line by line for large responses
332
processLine(line);
333
}
334
}
335
}
336
}
337
```
338
339
### Downloading Files
340
341
```java
342
HttpGet httpGet = new HttpGet("https://example.com/largefile.zip");
343
344
try (CloseableHttpResponse response = httpClient.execute(httpGet)) {
345
HttpEntity entity = response.getEntity();
346
347
if (entity != null) {
348
try (InputStream inputStream = entity.getContent();
349
FileOutputStream outputStream = new FileOutputStream("downloaded-file.zip")) {
350
351
byte[] buffer = new byte[8192];
352
int bytesRead;
353
while ((bytesRead = inputStream.read(buffer)) != -1) {
354
outputStream.write(buffer, 0, bytesRead);
355
}
356
}
357
}
358
}
359
```
360
361
## Response Interceptors
362
363
### HttpResponseInterceptor
364
365
```java { .api }
366
public interface HttpResponseInterceptor {
367
void process(HttpResponse response, HttpContext context) throws HttpException, IOException;
368
}
369
```
370
371
Interface for intercepting and processing HTTP responses.
372
373
```java
374
HttpResponseInterceptor responseInterceptor = new HttpResponseInterceptor() {
375
@Override
376
public void process(HttpResponse response, HttpContext context) throws HttpException, IOException {
377
// Log response details
378
StatusLine statusLine = response.getStatusLine();
379
System.out.println("Response: " + statusLine.getStatusCode() + " " + statusLine.getReasonPhrase());
380
381
// Add custom processing
382
Header serverHeader = response.getFirstHeader("Server");
383
if (serverHeader != null) {
384
System.out.println("Server: " + serverHeader.getValue());
385
}
386
}
387
};
388
389
CloseableHttpClient httpClient = HttpClients.custom()
390
.addInterceptorLast(responseInterceptor)
391
.build();
392
```
393
394
## Types
395
396
### ProtocolVersion
397
398
```java { .api }
399
public class ProtocolVersion implements Serializable, Cloneable {
400
public static final String HTTP = "HTTP";
401
402
public ProtocolVersion(String protocol, int major, int minor);
403
public final String getProtocol();
404
public final int getMajor();
405
public final int getMinor();
406
public ProtocolVersion forVersion(int major, int minor);
407
}
408
```
409
410
Represents HTTP protocol version information.
411
412
### Locale Support
413
414
```java { .api }
415
public interface HttpResponse extends HttpMessage {
416
Locale getLocale();
417
void setLocale(Locale loc);
418
}
419
```
420
421
HTTP responses support locale information for internationalization.
422
423
## Resource Management Utilities
424
425
### HttpClientUtils
426
427
```java { .api }
428
public final class HttpClientUtils {
429
public static void closeQuietly(HttpResponse response);
430
public static void closeQuietly(CloseableHttpResponse response);
431
public static void closeQuietly(HttpClient httpClient);
432
}
433
```
434
435
Utility methods for safely closing HTTP resources without throwing exceptions.
436
437
```java
438
CloseableHttpClient httpClient = HttpClients.createDefault();
439
CloseableHttpResponse response = null;
440
441
try {
442
HttpGet httpGet = new HttpGet("https://api.example.com");
443
response = httpClient.execute(httpGet);
444
445
// Process response
446
String responseBody = EntityUtils.toString(response.getEntity());
447
448
} catch (IOException e) {
449
// Handle exception
450
} finally {
451
// Safe cleanup
452
HttpClientUtils.closeQuietly(response);
453
HttpClientUtils.closeQuietly(httpClient);
454
}
455
```