View Javadoc

1   /*
2    * Copyright 2012 The Netty Project
3    *
4    * The Netty Project licenses this file to you under the Apache License,
5    * version 2.0 (the "License"); you may not use this file except in compliance
6    * with the License. You may obtain a copy of the License at:
7    *
8    *   http://www.apache.org/licenses/LICENSE-2.0
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12   * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13   * License for the specific language governing permissions and limitations
14   * under the License.
15   */
16  package io.netty.handler.codec.http;
17  
18  import io.netty.buffer.ByteBuf;
19  import io.netty.util.CharsetUtil;
20  
21  import static io.netty.handler.codec.http.HttpConstants.*;
22  
23  /**
24   * Encodes an {@link HttpRequest} or an {@link HttpContent} into
25   * a {@link ByteBuf}.
26   */
27  public class HttpRequestEncoder extends HttpObjectEncoder<HttpRequest> {
28      private static final char SLASH = '/';
29      private static final char QUESTION_MARK = '?';
30  
31      @Override
32      public boolean acceptOutboundMessage(Object msg) throws Exception {
33          return super.acceptOutboundMessage(msg) && !(msg instanceof HttpResponse);
34      }
35  
36      @Override
37      protected void encodeInitialLine(ByteBuf buf, HttpRequest request) throws Exception {
38          request.getMethod().encode(buf);
39          buf.writeByte(SP);
40  
41          // Add / as absolute path if no is present.
42          // See http://tools.ietf.org/html/rfc2616#section-5.1.2
43          String uri = request.getUri();
44  
45          if (uri.isEmpty()) {
46              uri += SLASH;
47          } else {
48              int start = uri.indexOf("://");
49              if (start != -1 && uri.charAt(0) != SLASH) {
50                  int startIndex = start + 3;
51                  // Correctly handle query params.
52                  // See https://github.com/netty/netty/issues/2732
53                  int index = uri.indexOf(QUESTION_MARK, startIndex);
54                  if (index == -1) {
55                      if (uri.lastIndexOf(SLASH) < startIndex) {
56                          uri += SLASH;
57                      }
58                  } else {
59                      if (uri.lastIndexOf(SLASH, index) < startIndex) {
60                          uri = new StringBuilder(uri).insert(index, SLASH).toString();
61                      }
62                  }
63              }
64          }
65  
66          buf.writeBytes(uri.getBytes(CharsetUtil.UTF_8));
67  
68          buf.writeByte(SP);
69          request.getProtocolVersion().encode(buf);
70          buf.writeBytes(CRLF);
71      }
72  }