Java Code Examples for io.netty.handler.codec.http.HttpHeaders#remove()

The following examples show how to use io.netty.handler.codec.http.HttpHeaders#remove() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: HttpHeaderCompressionTest.java    From netty-http2 with Apache License 2.0 6 votes vote down vote up
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    assertTrue(msg instanceof HttpHeaderBlockFrame);
    HttpHeaders actual = ((HttpHeaderBlockFrame) msg).headers();
    HttpHeaders expected = frame.headers();
    for (String name : expected.names()) {
        List<String> expectedValues = new ArrayList<String>(expected.getAll(name));
        List<String> actualValues = new ArrayList<String>(actual.getAll(name));
        assertTrue(actualValues.containsAll(expectedValues));
        actualValues.removeAll(expectedValues);
        assertTrue(actualValues.isEmpty());
        actual.remove(name);
    }
    assertTrue(actual.isEmpty());
    success = true;
}
 
Example 2
Source File: HttpConversionUtil.java    From netty-4.1.22 with Apache License 2.0 6 votes vote down vote up
/**
 * Translate and add HTTP/2 headers to HTTP/1.x headers.
 *
 * @param streamId The stream associated with {@code sourceHeaders}.
 * @param inputHeaders The HTTP/2 headers to convert.
 * @param outputHeaders The object which will contain the resulting HTTP/1.x headers..
 * @param httpVersion What HTTP/1.x version {@code outputHeaders} should be treated as when doing the conversion.
 * @param isTrailer {@code true} if {@code outputHeaders} should be treated as trailing headers.
 * {@code false} otherwise.
 * @param isRequest {@code true} if the {@code outputHeaders} will be used in a request message.
 * {@code false} for response message.
 * @throws Http2Exception If not all HTTP/2 headers can be translated to HTTP/1.x.
 */
public static void addHttp2ToHttpHeaders(int streamId, Http2Headers inputHeaders, HttpHeaders outputHeaders,
        HttpVersion httpVersion, boolean isTrailer, boolean isRequest) throws Http2Exception {
    Http2ToHttpHeaderTranslator translator = new Http2ToHttpHeaderTranslator(streamId, outputHeaders, isRequest);
    try {
        for (Entry<CharSequence, CharSequence> entry : inputHeaders) {
            translator.translate(entry);
        }
    } catch (Http2Exception ex) {
        throw ex;
    } catch (Throwable t) {
        throw streamError(streamId, PROTOCOL_ERROR, t, "HTTP/2 to HTTP/1.x headers conversion error");
    }

    outputHeaders.remove(HttpHeaderNames.TRANSFER_ENCODING);
    outputHeaders.remove(HttpHeaderNames.TRAILER);
    if (!isTrailer) {
        outputHeaders.setInt(ExtensionHeaderNames.STREAM_ID.text(), streamId);
        HttpUtil.setKeepAlive(outputHeaders, httpVersion, true);
    }
}
 
Example 3
Source File: HttpclientRequestHeadersInterceptor.java    From skywalking with Apache License 2.0 6 votes vote down vote up
@Override
public void beforeMethod(final EnhancedInstance objInst,
                         final Method method,
                         final Object[] allArguments,
                         final Class<?>[] argumentsTypes,
                         final MethodInterceptResult result) throws Throwable {
    CarrierItem next = (CarrierItem) objInst.getSkyWalkingDynamicField();
    if (next != null) {
        HttpHeaders headers = (HttpHeaders) allArguments[0];
        while (next.hasNext()) {
            next = next.next();
            headers.remove(next.getHeadKey());
            headers.set(next.getHeadKey(), next.getHeadValue());
        }
    }
}
 
Example 4
Source File: Http1RequestDecoder.java    From armeria with Apache License 2.0 6 votes vote down vote up
private boolean handle100Continue(int id, HttpRequest nettyReq, HttpHeaders nettyHeaders) {
    if (nettyReq.protocolVersion().compareTo(HttpVersion.HTTP_1_1) < 0) {
        // Ignore HTTP/1.0 requests.
        return true;
    }

    final String expectValue = nettyHeaders.get(HttpHeaderNames.EXPECT);
    if (expectValue == null) {
        // No 'expect' header.
        return true;
    }

    // '100-continue' is the only allowed expectation.
    if (!Ascii.equalsIgnoreCase("100-continue", expectValue)) {
        return false;
    }

    // Send a '100 Continue' response.
    writer.writeHeaders(id, 1, CONTINUE_RESPONSE, false);

    // Remove the 'expect' header so that it's handled in a way invisible to a Service.
    nettyHeaders.remove(HttpHeaderNames.EXPECT);
    return true;
}
 
Example 5
Source File: ProxyUtils.java    From g4proxy with Apache License 2.0 6 votes vote down vote up
/**
 * Given an HttpHeaders instance, removes 'sdch' from the 'Accept-Encoding'
 * header list (if it exists) and returns the modified instance.
 * <p>
 * Removes all occurrences of 'sdch' from the 'Accept-Encoding' header.
 *
 * @param headers The headers to modify.
 */
public static void removeSdchEncoding(HttpHeaders headers) {
    List<String> encodings = headers.getAll(HttpHeaders.Names.ACCEPT_ENCODING);
    headers.remove(HttpHeaders.Names.ACCEPT_ENCODING);

    for (String encoding : encodings) {
        if (encoding != null) {
            // The former regex should remove occurrences of 'sdch' while the
            // latter regex should take care of the dangling comma case when
            // 'sdch' was the first element in the list and there are other
            // encodings.
            encoding = encoding.replaceAll(",? *(sdch|SDCH)", "").replaceFirst("^ *, *", "");

            if (StringUtils.isNotBlank(encoding)) {
                headers.add(HttpHeaders.Names.ACCEPT_ENCODING, encoding);
            }
        }
    }
}
 
Example 6
Source File: ServerWebSocketContainer.java    From quarkus-http with Apache License 2.0 6 votes vote down vote up
@Override
public void afterRequest(final HttpHeaders headers) {
    ClientEndpointConfig.Configurator configurator = config.getConfigurator();
    if (configurator != null) {
        final Map<String, List<String>> newHeaders = new TreeMap<>(String.CASE_INSENSITIVE_ORDER);
        for (Map.Entry<String, String> entry : headers) {
            ArrayList<String> arrayList = new ArrayList<>(headers.getAll(entry.getKey()));
            newHeaders.put(entry.getKey(), arrayList);
        }
        configurator.afterResponse(new HandshakeResponse() {
            @Override
            public Map<String, List<String>> getHeaders() {
                return newHeaders;
            }
        });
    }
    headers.remove(HttpHeaderNames.SEC_WEBSOCKET_PROTOCOL);
    super.afterRequest(headers);
}
 
Example 7
Source File: ResponseSender.java    From riposte with Apache License 2.0 5 votes vote down vote up
protected void removeTransferEncodingChunked(HttpHeaders headers) {
    if (headers.contains(TRANSFER_ENCODING, CHUNKED, true)) {
        List<String> transferEncodingsMinusChunked =
            headers.getAll(TRANSFER_ENCODING).stream()
                   .filter(encoding -> !CHUNKED.equalsIgnoreCase(encoding))
                   .collect(Collectors.toList());

        if (transferEncodingsMinusChunked.isEmpty()) {
            headers.remove(TRANSFER_ENCODING);
        }
        else {
            headers.set(TRANSFER_ENCODING, transferEncodingsMinusChunked);
        }
    }
}
 
Example 8
Source File: StripUntrustedProxyHeadersHandler.java    From zuul with Apache License 2.0 5 votes vote down vote up
@VisibleForTesting
void stripXFFHeaders(HttpRequest req)
{
    HttpHeaders headers = req.headers();
    for (AsciiString headerName : HEADERS_TO_STRIP) {
        headers.remove(headerName);
    }
}
 
Example 9
Source File: FrontendIntegrationTest.java    From ambry with Apache License 2.0 5 votes vote down vote up
/**
 * Updates the TTL of the given {@code blobId} and verifies it by doing a BlobInfo.
 * @param blobId the blob ID of the blob to update and verify.
 * @param getExpectedHeaders the expected headers in the getBlobInfo response after the TTL update.
 * @param isPrivate {@code true} if the blob is expected to be private
 * @param accountName the expected account name in the response.
 * @param containerName the expected container name in response.
 * @param usermetadata if non-null, this is expected to come as the body.
 * @throws ExecutionException
 * @throws InterruptedException
 */
private void updateBlobTtlAndVerify(String blobId, HttpHeaders getExpectedHeaders, boolean isPrivate,
    String accountName, String containerName, byte[] usermetadata) throws ExecutionException, InterruptedException {
  HttpHeaders headers = new DefaultHttpHeaders();
  headers.set(RestUtils.Headers.BLOB_ID, addClusterPrefix ? "/" + CLUSTER_NAME + blobId : blobId);
  headers.set(RestUtils.Headers.SERVICE_ID, "updateBlobTtlAndVerify");
  FullHttpRequest httpRequest = buildRequest(HttpMethod.PUT, "/" + Operations.UPDATE_TTL, headers, null);
  ResponseParts responseParts = nettyClient.sendRequest(httpRequest, null, null).get();
  verifyUpdateBlobTtlResponse(responseParts);
  getExpectedHeaders.remove(RestUtils.Headers.TTL);
  getBlobInfoAndVerify(blobId, GetOption.None, getExpectedHeaders, isPrivate, accountName, containerName,
      usermetadata);
}
 
Example 10
Source File: SpdyHttpEncoder.java    From netty4.0.27Learn with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("deprecation")
private SpdyHeadersFrame createHeadersFrame(HttpResponse httpResponse) throws Exception {
    // Get the Stream-ID from the headers
    final HttpHeaders httpHeaders = httpResponse.headers();
    int streamId = SpdyHttpHeaders.getStreamId(httpResponse);
    httpHeaders.remove(SpdyHttpHeaders.Names.STREAM_ID);

    // The Connection, Keep-Alive, Proxy-Connection, and Transfer-Encoding
    // headers are not valid and MUST not be sent.
    httpHeaders.remove(HttpHeaders.Names.CONNECTION);
    httpHeaders.remove("Keep-Alive");
    httpHeaders.remove("Proxy-Connection");
    httpHeaders.remove(HttpHeaders.Names.TRANSFER_ENCODING);

    SpdyHeadersFrame spdyHeadersFrame;
    if (SpdyCodecUtil.isServerId(streamId)) {
        spdyHeadersFrame = new DefaultSpdyHeadersFrame(streamId);
    } else {
        spdyHeadersFrame = new DefaultSpdySynReplyFrame(streamId);
    }
    SpdyHeaders frameHeaders = spdyHeadersFrame.headers();
    // Unfold the first line of the response into name/value pairs
    frameHeaders.set(SpdyHeaders.HttpNames.STATUS, httpResponse.getStatus().code());
    frameHeaders.set(SpdyHeaders.HttpNames.VERSION, httpResponse.getProtocolVersion());

    // Transfer the remaining HTTP headers
    for (Map.Entry<String, String> entry: httpHeaders) {
        spdyHeadersFrame.headers().add(entry.getKey(), entry.getValue());
    }

    currentStreamId = streamId;
    spdyHeadersFrame.setLast(isLast(httpResponse));

    return spdyHeadersFrame;
}
 
Example 11
Source File: DiscordWebClient.java    From Discord4J with GNU Lesser General Public License v3.0 5 votes vote down vote up
private <R> HttpHeaders buildHttpHeaders(ClientRequest request) {
    HttpHeaders headers = new DefaultHttpHeaders().add(defaultHeaders).setAll(request.getHeaders());
    if (request.getBody() == null) {
        headers.remove(HttpHeaderNames.CONTENT_TYPE);
    }
    return headers;
}
 
Example 12
Source File: ClientToProxyConnection.java    From g4proxy with Apache License 2.0 5 votes vote down vote up
/**
 * Removes all headers that should not be forwarded. See RFC 2616 13.5.1
 * End-to-end and Hop-by-hop Headers.
 * 
 * @param headers
 *            The headers to modify
 */
private void stripHopByHopHeaders(HttpHeaders headers) {
    Set<String> headerNames = headers.names();
    for (String headerName : headerNames) {
        if (ProxyUtils.shouldRemoveHopByHopHeader(headerName)) {
            headers.remove(headerName);
        }
    }
}
 
Example 13
Source File: ClientToProxyConnection.java    From g4proxy with Apache License 2.0 5 votes vote down vote up
/**
 * RFC2616 Section 14.10
 * 
 * HTTP/1.1 proxies MUST parse the Connection header field before a message
 * is forwarded and, for each connection-token in this field, remove any
 * header field(s) from the message with the same name as the
 * connection-token.
 * 
 * @param headers
 *            The headers to modify
 */
private void stripConnectionTokens(HttpHeaders headers) {
    if (headers.contains(HttpHeaders.Names.CONNECTION)) {
        for (String headerValue : headers.getAll(HttpHeaders.Names.CONNECTION)) {
            for (String connectionToken : ProxyUtils.splitCommaSeparatedHeaderValues(headerValue)) {
                // do not strip out the Transfer-Encoding header if it is specified in the Connection header, since LittleProxy does not
                // normally modify the Transfer-Encoding of the message.
                if (!LOWERCASE_TRANSFER_ENCODING_HEADER.equals(connectionToken.toLowerCase(Locale.US))) {
                    headers.remove(connectionToken);
                }
            }
        }
    }
}
 
Example 14
Source File: ClientToProxyConnection.java    From g4proxy with Apache License 2.0 5 votes vote down vote up
/**
 * Switch the de-facto standard "Proxy-Connection" header to "Connection"
 * when we pass it along to the remote host. This is largely undocumented
 * but seems to be what most browsers and servers expect.
 * 
 * @param headers
 *            The headers to modify
 */
private void switchProxyConnectionHeader(HttpHeaders headers) {
    String proxyConnectionKey = "Proxy-Connection";
    if (headers.contains(proxyConnectionKey)) {
        String header = headers.get(proxyConnectionKey);
        headers.remove(proxyConnectionKey);
        headers.set(HttpHeaders.Names.CONNECTION, header);
    }
}
 
Example 15
Source File: SpdyHttpEncoder.java    From netty-4.1.22 with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("deprecation")
private SpdyHeadersFrame createHeadersFrame(HttpResponse httpResponse) throws Exception {
    // Get the Stream-ID from the headers
    final HttpHeaders httpHeaders = httpResponse.headers();
    int streamId = httpHeaders.getInt(SpdyHttpHeaders.Names.STREAM_ID);
    httpHeaders.remove(SpdyHttpHeaders.Names.STREAM_ID);

    // The Connection, Keep-Alive, Proxy-Connection, and Transfer-Encoding
    // headers are not valid and MUST not be sent.
    httpHeaders.remove(HttpHeaderNames.CONNECTION);
    httpHeaders.remove("Keep-Alive");
    httpHeaders.remove("Proxy-Connection");
    httpHeaders.remove(HttpHeaderNames.TRANSFER_ENCODING);

    SpdyHeadersFrame spdyHeadersFrame;
    if (SpdyCodecUtil.isServerId(streamId)) {
        spdyHeadersFrame = new DefaultSpdyHeadersFrame(streamId, validateHeaders);
    } else {
        spdyHeadersFrame = new DefaultSpdySynReplyFrame(streamId, validateHeaders);
    }
    SpdyHeaders frameHeaders = spdyHeadersFrame.headers();
    // Unfold the first line of the response into name/value pairs
    frameHeaders.set(SpdyHeaders.HttpNames.STATUS, httpResponse.status().codeAsText());
    frameHeaders.set(SpdyHeaders.HttpNames.VERSION, httpResponse.protocolVersion().text());

    // Transfer the remaining HTTP headers
    Iterator<Entry<CharSequence, CharSequence>> itr = httpHeaders.iteratorCharSequence();
    while (itr.hasNext()) {
        Map.Entry<CharSequence, CharSequence> entry = itr.next();
        final CharSequence headerName =
                headersToLowerCase ? AsciiString.of(entry.getKey()).toLowerCase() : entry.getKey();
        spdyHeadersFrame.headers().add(headerName, entry.getValue());
    }

    currentStreamId = streamId;
    spdyHeadersFrame.setLast(isLast(httpResponse));

    return spdyHeadersFrame;
}
 
Example 16
Source File: ServletOutputStream.java    From spring-boot-protocol with Apache License 2.0 4 votes vote down vote up
/**
     * Set the response header
     * @param isKeepAlive keep alive
     * @param nettyResponse nettyResponse
     * @param servletRequest servletRequest
     * @param servletResponse servletResponse
     * @param sessionCookieConfig sessionCookieConfig
     */
    private static void settingResponseHeader(boolean isKeepAlive, NettyHttpResponse nettyResponse,
                                              ServletHttpServletRequest servletRequest, ServletHttpServletResponse servletResponse,
                                              ServletSessionCookieConfig sessionCookieConfig) {
        HttpHeaderUtil.setKeepAlive(nettyResponse, isKeepAlive);
        HttpHeaders headers = nettyResponse.headers();

        //Content length
        long contentLength = servletResponse.getContentLength();
        if(contentLength >= 0) {
            headers.remove(HttpHeaderConstants.TRANSFER_ENCODING);
            headers.set(HttpHeaderConstants.CONTENT_LENGTH, contentLength);
        }else {
            nettyResponse.enableTransferEncodingChunked();
        }

        // Time and date response header
        if(!headers.contains(HttpHeaderConstants.DATE)) {
            headers.set(HttpHeaderConstants.DATE, ServletUtil.getDateByRfcHttp());
        }

        //Content Type The content of the response header
        String contentType = servletResponse.getContentType();
        if (null != contentType) {
            String characterEncoding = servletResponse.getCharacterEncoding();
            String value = (null == characterEncoding) ? contentType :
                    RecyclableUtil.newStringBuilder()
                            .append(contentType)
                            .append(APPEND_CONTENT_TYPE)
                            .append(characterEncoding).toString();
            headers.set(HttpHeaderConstants.CONTENT_TYPE, value);
        }

        //Server information response header
        String serverHeader = servletRequest.getServletContext().getServerHeader();
        if(serverHeader != null && serverHeader.length() > 0) {
            headers.set(HttpHeaderConstants.SERVER, serverHeader);
        }

        //language
        Locale locale = servletResponse.getLocale();
        if(!headers.contains(HttpHeaderConstants.CONTENT_LANGUAGE)){
            headers.set(HttpHeaderConstants.CONTENT_LANGUAGE,locale.toLanguageTag());
        }

        // Cookies processing
        //Session is handled first. If it is a new Session and the Session id is not the same as the Session id passed by the request, it needs to be written through the Cookie
        List<Cookie> cookies = servletResponse.getCookies();
        ServletHttpSession httpSession = servletRequest.getSession(false);
        if (httpSession != null && httpSession.isNew()
//		        && !httpSession.getId().equals(servletRequest.getRequestedSessionId())
        ) {
            String sessionCookieName = sessionCookieConfig.getName();
            if(sessionCookieName == null || sessionCookieName.isEmpty()){
                sessionCookieName = HttpConstants.JSESSION_ID_COOKIE;
            }
            String sessionCookiePath = sessionCookieConfig.getPath();
            if(sessionCookiePath == null || sessionCookiePath.isEmpty()) {
                sessionCookiePath = HttpConstants.DEFAULT_SESSION_COOKIE_PATH;
            }
            String sessionCookieText = ServletUtil.encodeCookie(sessionCookieName,servletRequest.getRequestedSessionId(), -1,
                    sessionCookiePath,sessionCookieConfig.getDomain(),sessionCookieConfig.isSecure(),Boolean.TRUE);
            headers.add(HttpHeaderConstants.SET_COOKIE, sessionCookieText);

            httpSession.setNewSessionFlag(false);
        }

        //Cookies set by other businesses or frameworks are written to the response header one by one
        int cookieSize = cookies.size();
        if(cookieSize > 0) {
            for (int i=0; i<cookieSize; i++) {
                Cookie cookie = cookies.get(i);
                String cookieText = ServletUtil.encodeCookie(cookie.getName(),cookie.getValue(),cookie.getMaxAge(),cookie.getPath(),cookie.getDomain(),cookie.getSecure(),cookie.isHttpOnly());
                headers.add(HttpHeaderConstants.SET_COOKIE, cookieText);
            }
        }
    }
 
Example 17
Source File: HttpPostRequestEncoder.java    From netty4.0.27Learn with Apache License 2.0 4 votes vote down vote up
/**
 * Finalize the request by preparing the Header in the request and returns the request ready to be sent.<br>
 * Once finalized, no data must be added.<br>
 * If the request does not need chunk (isChunked() == false), this request is the only object to send to the remote
 * server.
 *
 * @return the request object (chunked or not according to size of body)
 * @throws ErrorDataEncoderException
 *             if the encoding is in error or if the finalize were already done
 */
public HttpRequest finalizeRequest() throws ErrorDataEncoderException {
    // Finalize the multipartHttpDatas
    if (!headerFinalized) {
        if (isMultipart) {
            InternalAttribute internal = new InternalAttribute(charset);
            if (duringMixedMode) {
                internal.addValue("\r\n--" + multipartMixedBoundary + "--");
            }
            internal.addValue("\r\n--" + multipartDataBoundary + "--\r\n");
            multipartHttpDatas.add(internal);
            multipartMixedBoundary = null;
            currentFileUpload = null;
            duringMixedMode = false;
            globalBodySize += internal.size();
        }
        headerFinalized = true;
    } else {
        throw new ErrorDataEncoderException("Header already encoded");
    }

    HttpHeaders headers = request.headers();
    List<String> contentTypes = headers.getAll(HttpHeaders.Names.CONTENT_TYPE);
    List<String> transferEncoding = headers.getAll(HttpHeaders.Names.TRANSFER_ENCODING);
    if (contentTypes != null) {
        headers.remove(HttpHeaders.Names.CONTENT_TYPE);
        for (String contentType : contentTypes) {
            // "multipart/form-data; boundary=--89421926422648"
            String lowercased = contentType.toLowerCase();
            if (lowercased.startsWith(HttpHeaders.Values.MULTIPART_FORM_DATA) ||
                lowercased.startsWith(HttpHeaders.Values.APPLICATION_X_WWW_FORM_URLENCODED)) {
                // ignore
            } else {
                headers.add(HttpHeaders.Names.CONTENT_TYPE, contentType);
            }
        }
    }
    if (isMultipart) {
        String value = HttpHeaders.Values.MULTIPART_FORM_DATA + "; " + HttpHeaders.Values.BOUNDARY + '='
                + multipartDataBoundary;
        headers.add(HttpHeaders.Names.CONTENT_TYPE, value);
    } else {
        // Not multipart
        headers.add(HttpHeaders.Names.CONTENT_TYPE, HttpHeaders.Values.APPLICATION_X_WWW_FORM_URLENCODED);
    }
    // Now consider size for chunk or not
    long realSize = globalBodySize;
    if (isMultipart) {
        iterator = multipartHttpDatas.listIterator();
    } else {
        realSize -= 1; // last '&' removed
        iterator = multipartHttpDatas.listIterator();
    }
    headers.set(HttpHeaders.Names.CONTENT_LENGTH, String.valueOf(realSize));
    if (realSize > HttpPostBodyUtil.chunkSize || isMultipart) {
        isChunked = true;
        if (transferEncoding != null) {
            headers.remove(HttpHeaders.Names.TRANSFER_ENCODING);
            for (String v : transferEncoding) {
                if (v.equalsIgnoreCase(HttpHeaders.Values.CHUNKED)) {
                    // ignore
                } else {
                    headers.add(HttpHeaders.Names.TRANSFER_ENCODING, v);
                }
            }
        }
        HttpHeaders.setTransferEncodingChunked(request);

        // wrap to hide the possible content
        return new WrappedHttpRequest(request);
    } else {
        // get the only one body and set it to the request
        HttpContent chunk = nextChunk();
        if (request instanceof FullHttpRequest) {
            FullHttpRequest fullRequest = (FullHttpRequest) request;
            ByteBuf chunkContent = chunk.content();
            if (fullRequest.content() != chunkContent) {
                fullRequest.content().clear().writeBytes(chunkContent);
                chunkContent.release();
            }
            return fullRequest;
        } else {
            return new WrappedFullHttpRequest(request, chunk);
        }
    }
}
 
Example 18
Source File: SpdyHttpEncoder.java    From netty4.0.27Learn with Apache License 2.0 4 votes vote down vote up
@SuppressWarnings("deprecation")
private SpdySynStreamFrame createSynStreamFrame(HttpRequest httpRequest) throws Exception {
    // Get the Stream-ID, Associated-To-Stream-ID, Priority, and scheme from the headers
    final HttpHeaders httpHeaders = httpRequest.headers();
    int streamId = SpdyHttpHeaders.getStreamId(httpRequest);
    int associatedToStreamId = SpdyHttpHeaders.getAssociatedToStreamId(httpRequest);
    byte priority = SpdyHttpHeaders.getPriority(httpRequest);
    CharSequence scheme = httpHeaders.get(SpdyHttpHeaders.Names.SCHEME);
    httpHeaders.remove(SpdyHttpHeaders.Names.STREAM_ID);
    httpHeaders.remove(SpdyHttpHeaders.Names.ASSOCIATED_TO_STREAM_ID);
    httpHeaders.remove(SpdyHttpHeaders.Names.PRIORITY);
    httpHeaders.remove(SpdyHttpHeaders.Names.SCHEME);

    // The Connection, Keep-Alive, Proxy-Connection, and Transfer-Encoding
    // headers are not valid and MUST not be sent.
    httpHeaders.remove(HttpHeaders.Names.CONNECTION);
    httpHeaders.remove("Keep-Alive");
    httpHeaders.remove("Proxy-Connection");
    httpHeaders.remove(HttpHeaders.Names.TRANSFER_ENCODING);

    SpdySynStreamFrame spdySynStreamFrame =
            new DefaultSpdySynStreamFrame(streamId, associatedToStreamId, priority);

    // Unfold the first line of the message into name/value pairs
    SpdyHeaders frameHeaders = spdySynStreamFrame.headers();
    frameHeaders.set(SpdyHeaders.HttpNames.METHOD, httpRequest.getMethod());
    frameHeaders.set(SpdyHeaders.HttpNames.PATH, httpRequest.getUri());
    frameHeaders.set(SpdyHeaders.HttpNames.VERSION, httpRequest.getProtocolVersion());

    // Replace the HTTP host header with the SPDY host header
    CharSequence host = httpHeaders.get(HttpHeaders.Names.HOST);
    httpHeaders.remove(HttpHeaders.Names.HOST);
    frameHeaders.set(SpdyHeaders.HttpNames.HOST, host);

    // Set the SPDY scheme header
    if (scheme == null) {
        scheme = "https";
    }
    frameHeaders.set(SpdyHeaders.HttpNames.SCHEME, scheme);

    // Transfer the remaining HTTP headers
    for (Map.Entry<String, String> entry: httpHeaders) {
        frameHeaders.add(entry.getKey(), entry.getValue());
    }
    currentStreamId = spdySynStreamFrame.streamId();
    if (associatedToStreamId == 0) {
        spdySynStreamFrame.setLast(isLast(httpRequest));
    } else {
        spdySynStreamFrame.setUnidirectional(true);
    }

    return spdySynStreamFrame;
}
 
Example 19
Source File: SpdyHttpEncoder.java    From netty-4.1.22 with Apache License 2.0 4 votes vote down vote up
@SuppressWarnings("deprecation")
private SpdySynStreamFrame createSynStreamFrame(HttpRequest httpRequest) throws Exception {
    // Get the Stream-ID, Associated-To-Stream-ID, Priority, and scheme from the headers
    final HttpHeaders httpHeaders = httpRequest.headers();
    int streamId = httpHeaders.getInt(SpdyHttpHeaders.Names.STREAM_ID);
    int associatedToStreamId = httpHeaders.getInt(SpdyHttpHeaders.Names.ASSOCIATED_TO_STREAM_ID, 0);
    byte priority = (byte) httpHeaders.getInt(SpdyHttpHeaders.Names.PRIORITY, 0);
    CharSequence scheme = httpHeaders.get(SpdyHttpHeaders.Names.SCHEME);
    httpHeaders.remove(SpdyHttpHeaders.Names.STREAM_ID);
    httpHeaders.remove(SpdyHttpHeaders.Names.ASSOCIATED_TO_STREAM_ID);
    httpHeaders.remove(SpdyHttpHeaders.Names.PRIORITY);
    httpHeaders.remove(SpdyHttpHeaders.Names.SCHEME);

    // The Connection, Keep-Alive, Proxy-Connection, and Transfer-Encoding
    // headers are not valid and MUST not be sent.
    httpHeaders.remove(HttpHeaderNames.CONNECTION);
    httpHeaders.remove("Keep-Alive");
    httpHeaders.remove("Proxy-Connection");
    httpHeaders.remove(HttpHeaderNames.TRANSFER_ENCODING);

    SpdySynStreamFrame spdySynStreamFrame =
            new DefaultSpdySynStreamFrame(streamId, associatedToStreamId, priority, validateHeaders);

    // Unfold the first line of the message into name/value pairs
    SpdyHeaders frameHeaders = spdySynStreamFrame.headers();
    frameHeaders.set(SpdyHeaders.HttpNames.METHOD, httpRequest.method().name());
    frameHeaders.set(SpdyHeaders.HttpNames.PATH, httpRequest.uri());
    frameHeaders.set(SpdyHeaders.HttpNames.VERSION, httpRequest.protocolVersion().text());

    // Replace the HTTP host header with the SPDY host header
    CharSequence host = httpHeaders.get(HttpHeaderNames.HOST);
    httpHeaders.remove(HttpHeaderNames.HOST);
    frameHeaders.set(SpdyHeaders.HttpNames.HOST, host);

    // Set the SPDY scheme header
    if (scheme == null) {
        scheme = "https";
    }
    frameHeaders.set(SpdyHeaders.HttpNames.SCHEME, scheme);

    // Transfer the remaining HTTP headers
    Iterator<Entry<CharSequence, CharSequence>> itr = httpHeaders.iteratorCharSequence();
    while (itr.hasNext()) {
        Map.Entry<CharSequence, CharSequence> entry = itr.next();
        final CharSequence headerName =
                headersToLowerCase ? AsciiString.of(entry.getKey()).toLowerCase() : entry.getKey();
        frameHeaders.add(headerName, entry.getValue());
    }
    currentStreamId = spdySynStreamFrame.streamId();
    if (associatedToStreamId == 0) {
        spdySynStreamFrame.setLast(isLast(httpRequest));
    } else {
        spdySynStreamFrame.setUnidirectional(true);
    }

    return spdySynStreamFrame;
}
 
Example 20
Source File: HttpPostRequestEncoder.java    From netty-4.1.22 with Apache License 2.0 4 votes vote down vote up
/**
 * Finalize the request by preparing the Header in the request and returns the request ready to be sent.<br>
 * Once finalized, no data must be added.<br>
 * If the request does not need chunk (isChunked() == false), this request is the only object to send to the remote
 * server.通过准备请求中的标头完成请求,并返回准备发送的请求。一旦确定,就不需要添加任何数据。如果请求不需要chunk (isChunked() == false),此请求是发送到远程服务器的唯一对象。
 *
 * @return the request object (chunked or not according to size of body)
 * @throws ErrorDataEncoderException
 *             if the encoding is in error or if the finalize were already done
 */
public HttpRequest finalizeRequest() throws ErrorDataEncoderException {
    // Finalize the multipartHttpDatas
    if (!headerFinalized) {
        if (isMultipart) {
            InternalAttribute internal = new InternalAttribute(charset);
            if (duringMixedMode) {
                internal.addValue("\r\n--" + multipartMixedBoundary + "--");
            }
            internal.addValue("\r\n--" + multipartDataBoundary + "--\r\n");
            multipartHttpDatas.add(internal);
            multipartMixedBoundary = null;
            currentFileUpload = null;
            duringMixedMode = false;
            globalBodySize += internal.size();
        }
        headerFinalized = true;
    } else {
        throw new ErrorDataEncoderException("Header already encoded");
    }

    HttpHeaders headers = request.headers();
    List<String> contentTypes = headers.getAll(HttpHeaderNames.CONTENT_TYPE);
    List<String> transferEncoding = headers.getAll(HttpHeaderNames.TRANSFER_ENCODING);
    if (contentTypes != null) {
        headers.remove(HttpHeaderNames.CONTENT_TYPE);
        for (String contentType : contentTypes) {
            // "multipart/form-data; boundary=--89421926422648"
            String lowercased = contentType.toLowerCase();
            if (lowercased.startsWith(HttpHeaderValues.MULTIPART_FORM_DATA.toString()) ||
                    lowercased.startsWith(HttpHeaderValues.APPLICATION_X_WWW_FORM_URLENCODED.toString())) {
                // ignore
            } else {
                headers.add(HttpHeaderNames.CONTENT_TYPE, contentType);
            }
        }
    }
    if (isMultipart) {
        String value = HttpHeaderValues.MULTIPART_FORM_DATA + "; " + HttpHeaderValues.BOUNDARY + '='
                + multipartDataBoundary;
        headers.add(HttpHeaderNames.CONTENT_TYPE, value);
    } else {
        // Not multipart
        headers.add(HttpHeaderNames.CONTENT_TYPE, HttpHeaderValues.APPLICATION_X_WWW_FORM_URLENCODED);
    }
    // Now consider size for chunk or not
    long realSize = globalBodySize;
    if (isMultipart) {
        iterator = multipartHttpDatas.listIterator();
    } else {
        realSize -= 1; // last '&' removed
        iterator = multipartHttpDatas.listIterator();
    }
    headers.set(HttpHeaderNames.CONTENT_LENGTH, String.valueOf(realSize));
    if (realSize > HttpPostBodyUtil.chunkSize || isMultipart) {
        isChunked = true;
        if (transferEncoding != null) {
            headers.remove(HttpHeaderNames.TRANSFER_ENCODING);
            for (CharSequence v : transferEncoding) {
                if (HttpHeaderValues.CHUNKED.contentEqualsIgnoreCase(v)) {
                    // ignore
                } else {
                    headers.add(HttpHeaderNames.TRANSFER_ENCODING, v);
                }
            }
        }
        HttpUtil.setTransferEncodingChunked(request, true);

        // wrap to hide the possible content
        return new WrappedHttpRequest(request);
    } else {
        // get the only one body and set it to the request
        HttpContent chunk = nextChunk();
        if (request instanceof FullHttpRequest) {
            FullHttpRequest fullRequest = (FullHttpRequest) request;
            ByteBuf chunkContent = chunk.content();
            if (fullRequest.content() != chunkContent) {
                fullRequest.content().clear().writeBytes(chunkContent);
                chunkContent.release();
            }
            return fullRequest;
        } else {
            return new WrappedFullHttpRequest(request, chunk);
        }
    }
}