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.protocol;
29
30 import java.io.IOException;
31
32 import org.apache.http.Header;
33 import org.apache.http.HttpEntity;
34 import org.apache.http.HttpException;
35 import org.apache.http.HttpRequest;
36 import org.apache.http.HttpResponse;
37 import org.apache.http.HttpResponseInterceptor;
38 import org.apache.http.HttpStatus;
39 import org.apache.http.HttpVersion;
40 import org.apache.http.ProtocolVersion;
41 import org.apache.http.annotation.Immutable;
42
43
44
45
46
47
48
49
50
51 @Immutable
52 public class ResponseConnControl implements HttpResponseInterceptor {
53
54 public ResponseConnControl() {
55 super();
56 }
57
58 public void process(final HttpResponse response, final HttpContext context)
59 throws HttpException, IOException {
60 if (response == null) {
61 throw new IllegalArgumentException("HTTP response may not be null");
62 }
63 if (context == null) {
64 throw new IllegalArgumentException("HTTP context may not be null");
65 }
66
67 int status = response.getStatusLine().getStatusCode();
68 if (status == HttpStatus.SC_BAD_REQUEST ||
69 status == HttpStatus.SC_REQUEST_TIMEOUT ||
70 status == HttpStatus.SC_LENGTH_REQUIRED ||
71 status == HttpStatus.SC_REQUEST_TOO_LONG ||
72 status == HttpStatus.SC_REQUEST_URI_TOO_LONG ||
73 status == HttpStatus.SC_SERVICE_UNAVAILABLE ||
74 status == HttpStatus.SC_NOT_IMPLEMENTED) {
75 response.setHeader(HTTP.CONN_DIRECTIVE, HTTP.CONN_CLOSE);
76 return;
77 }
78 Header explicit = response.getFirstHeader(HTTP.CONN_DIRECTIVE);
79 if (explicit != null && HTTP.CONN_CLOSE.equalsIgnoreCase(explicit.getValue())) {
80
81 return;
82 }
83
84
85 HttpEntity entity = response.getEntity();
86 if (entity != null) {
87 ProtocolVersion ver = response.getStatusLine().getProtocolVersion();
88 if (entity.getContentLength() < 0 &&
89 (!entity.isChunked() || ver.lessEquals(HttpVersion.HTTP_1_0))) {
90 response.setHeader(HTTP.CONN_DIRECTIVE, HTTP.CONN_CLOSE);
91 return;
92 }
93 }
94
95 HttpRequest request = (HttpRequest)
96 context.getAttribute(ExecutionContext.HTTP_REQUEST);
97 if (request != null) {
98 Header header = request.getFirstHeader(HTTP.CONN_DIRECTIVE);
99 if (header != null) {
100 response.setHeader(HTTP.CONN_DIRECTIVE, header.getValue());
101 } else if (request.getProtocolVersion().lessEquals(HttpVersion.HTTP_1_0)) {
102 response.setHeader(HTTP.CONN_DIRECTIVE, HTTP.CONN_CLOSE);
103 }
104 }
105 }
106
107 }