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.ThreadingBehavior;
42 import org.apache.http.annotation.Contract;
43 import org.apache.http.util.Args;
44
45
46
47
48
49
50
51
52
53 @Contract(threading = ThreadingBehavior.IMMUTABLE)
54 public class ResponseConnControl implements HttpResponseInterceptor {
55
56 public ResponseConnControl() {
57 super();
58 }
59
60 @Override
61 public void process(final HttpResponse response, final HttpContext context)
62 throws HttpException, IOException {
63 Args.notNull(response, "HTTP response");
64
65 final HttpCoreContext corecontext = HttpCoreContext.adapt(context);
66
67
68 final int status = response.getStatusLine().getStatusCode();
69 if (status == HttpStatus.SC_BAD_REQUEST ||
70 status == HttpStatus.SC_REQUEST_TIMEOUT ||
71 status == HttpStatus.SC_LENGTH_REQUIRED ||
72 status == HttpStatus.SC_REQUEST_TOO_LONG ||
73 status == HttpStatus.SC_REQUEST_URI_TOO_LONG ||
74 status == HttpStatus.SC_SERVICE_UNAVAILABLE ||
75 status == HttpStatus.SC_NOT_IMPLEMENTED) {
76 response.setHeader(HTTP.CONN_DIRECTIVE, HTTP.CONN_CLOSE);
77 return;
78 }
79 final Header explicit = response.getFirstHeader(HTTP.CONN_DIRECTIVE);
80 if (explicit != null && HTTP.CONN_CLOSE.equalsIgnoreCase(explicit.getValue())) {
81
82 return;
83 }
84
85
86 final HttpEntity entity = response.getEntity();
87 if (entity != null) {
88 final ProtocolVersion ver = response.getStatusLine().getProtocolVersion();
89 if (entity.getContentLength() < 0 &&
90 (!entity.isChunked() || ver.lessEquals(HttpVersion.HTTP_1_0))) {
91 response.setHeader(HTTP.CONN_DIRECTIVE, HTTP.CONN_CLOSE);
92 return;
93 }
94 }
95
96 final HttpRequest request = corecontext.getRequest();
97 if (request != null) {
98 final 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 }