|
| 1 | +/* |
| 2 | + * Copyright (c) 2014 AsyncHttpClient Project. All rights reserved. |
| 3 | + * |
| 4 | + * This program is licensed to you under the Apache License Version 2.0, |
| 5 | + * and you may not use this file except in compliance with the Apache License Version 2.0. |
| 6 | + * You may obtain a copy of the Apache License Version 2.0 at |
| 7 | + * http://www.apache.org/licenses/LICENSE-2.0. |
| 8 | + * |
| 9 | + * Unless required by applicable law or agreed to in writing, |
| 10 | + * software distributed under the Apache License Version 2.0 is distributed on an |
| 11 | + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | + * See the Apache License Version 2.0 for the specific language governing permissions and limitations there under. |
| 13 | + */ |
| 14 | +package com.ning.http.client.providers.netty.handler; |
| 15 | + |
| 16 | +import static org.jboss.netty.handler.codec.http.HttpHeaders.Names.*; |
| 17 | +import static org.jboss.netty.handler.codec.http.HttpHeaders.Values.*; |
| 18 | + |
| 19 | +import org.jboss.netty.handler.codec.http.HttpMessage; |
| 20 | +import org.jboss.netty.handler.codec.http.HttpRequest; |
| 21 | +import org.jboss.netty.handler.codec.http.HttpResponse; |
| 22 | +import org.jboss.netty.handler.codec.http.HttpVersion; |
| 23 | + |
| 24 | +/** |
| 25 | + * Connection strategy implementing standard HTTP 1.0 and 1.1 behaviour. |
| 26 | + */ |
| 27 | +public class DefaultConnectionStrategy implements ConnectionStrategy { |
| 28 | + |
| 29 | + /** |
| 30 | + * Implemented in accordance with RFC 7230 section 6.1 |
| 31 | + * https://tools.ietf.org/html/rfc7230#section-6.1 |
| 32 | + */ |
| 33 | + @Override |
| 34 | + public boolean keepAlive(HttpRequest request, HttpResponse response) { |
| 35 | + |
| 36 | + String responseConnectionHeader = connectionHeader(response); |
| 37 | + |
| 38 | + |
| 39 | + if (CLOSE.equalsIgnoreCase(responseConnectionHeader)) { |
| 40 | + return false; |
| 41 | + } else { |
| 42 | + String requestConnectionHeader = connectionHeader(request); |
| 43 | + |
| 44 | + if (request.getProtocolVersion() == HttpVersion.HTTP_1_0) { |
| 45 | + // only use keep-alive if both parties agreed upon it |
| 46 | + return KEEP_ALIVE.equalsIgnoreCase(requestConnectionHeader) && KEEP_ALIVE.equalsIgnoreCase(responseConnectionHeader); |
| 47 | + |
| 48 | + } else { |
| 49 | + // 1.1+, keep-alive is default behavior |
| 50 | + return !CLOSE.equalsIgnoreCase(requestConnectionHeader); |
| 51 | + } |
| 52 | + } |
| 53 | + } |
| 54 | + |
| 55 | + private String connectionHeader(HttpMessage message) { |
| 56 | + return message.headers().get(CONNECTION); |
| 57 | + } |
| 58 | +} |
0 commit comments