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

The following examples show how to use io.netty.handler.codec.http.HttpHeaders#setTransferEncodingChunked() . 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: AsyncRESTHandler.java    From arcusplatform with Apache License 2.0 5 votes vote down vote up
protected FullHttpResponse response(HttpResponseStatus status, String contentType, String contents) {
	FullHttpResponse httpResponse = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, status,
			Unpooled.copiedBuffer(contents, CharsetUtil.UTF_8));
	if (restHandlerConfig.isSendChunked()) {
		HttpHeaders.setTransferEncodingChunked(httpResponse);
	}
	httpResponse.headers().set(HttpHeaders.Names.CONTENT_TYPE, contentType);
	return httpResponse;
}
 
Example 2
Source File: HttpResponseOutputStream.java    From Jinx with Apache License 2.0 5 votes vote down vote up
private void writeResponse(boolean lastContent) {
    HttpResponse response = servletResponse.getNettyResponse();
    // TODO implement exceptions required by http://tools.ietf.org/html/rfc2616#section-4.4
    if (!HttpHeaders.isContentLengthSet(response)) {
        if (lastContent) {
            HttpHeaders.setContentLength(response, count);
        } else {
            HttpHeaders.setTransferEncodingChunked(response);
        }
    }
    ctx.write(response, ctx.voidPromise());
}
 
Example 3
Source File: HttpResponseOutputStream.java    From spring-boot-starter-netty with Apache License 2.0 5 votes vote down vote up
private void writeResponse(boolean lastContent) {
    HttpResponse response = servletResponse.getNettyResponse();
    // TODO implement exceptions required by http://tools.ietf.org/html/rfc2616#section-4.4
    if (!HttpHeaders.isContentLengthSet(response)) {
        if (lastContent) {
            HttpHeaders.setContentLength(response, count);
        } else {
            HttpHeaders.setTransferEncodingChunked(response);
        }
    }
    ctx.write(response, ctx.voidPromise());
}
 
Example 4
Source File: ClientToProxyConnection.java    From g4proxy with Apache License 2.0 4 votes vote down vote up
/**
 * Send a response to the client.
 * 
 * @param serverConnection
 *            the ProxyToServerConnection that's responding
 * @param filters
 *            the filters to apply to the response
 * @param currentHttpRequest
 *            the HttpRequest that prompted this response
 * @param currentHttpResponse
 *            the HttpResponse corresponding to this data (when doing
 *            chunked transfers, this is the initial HttpResponse object
 *            that came in before the other chunks)
 * @param httpObject
 *            the data with which to respond
 */
void respond(ProxyToServerConnection serverConnection, HttpFilters filters,
        HttpRequest currentHttpRequest, HttpResponse currentHttpResponse,
        HttpObject httpObject) {
    // we are sending a response to the client, so we are done handling this request
    this.currentRequest = null;

    httpObject = filters.serverToProxyResponse(httpObject);
    if (httpObject == null) {
        forceDisconnect(serverConnection);
        return;
    }

    if (httpObject instanceof HttpResponse) {
        HttpResponse httpResponse = (HttpResponse) httpObject;

        // if this HttpResponse does not have any means of signaling the end of the message body other than closing
        // the connection, convert the message to a "Transfer-Encoding: chunked" HTTP response. This avoids the need
        // to close the client connection to indicate the end of the message. (Responses to HEAD requests "must be" empty.)
        if (!ProxyUtils.isHEAD(currentHttpRequest) && !ProxyUtils.isResponseSelfTerminating(httpResponse)) {
            // if this is not a FullHttpResponse,  duplicate the HttpResponse from the server before sending it to
            // the client. this allows us to set the Transfer-Encoding to chunked without interfering with netty's
            // handling of the response from the server. if we modify the original HttpResponse from the server,
            // netty will not generate the appropriate LastHttpContent when it detects the connection closure from
            // the server (see HttpObjectDecoder#decodeLast). (This does not apply to FullHttpResponses, for which
            // netty already generates the empty final chunk when Transfer-Encoding is chunked.)
            if (!(httpResponse instanceof FullHttpResponse)) {
                HttpResponse duplicateResponse = ProxyUtils.duplicateHttpResponse(httpResponse);

                // set the httpObject and httpResponse to the duplicated response, to allow all other standard processing
                // (filtering, header modification for proxying, etc.) to be applied.
                httpObject = httpResponse = duplicateResponse;
            }

            HttpHeaders.setTransferEncodingChunked(httpResponse);
        }

        fixHttpVersionHeaderIfNecessary(httpResponse);
        modifyResponseHeadersToReflectProxying(httpResponse);
    }

    httpObject = filters.proxyToClientResponse(httpObject);
    if (httpObject == null) {
        forceDisconnect(serverConnection);
        return;
    }

    write(httpObject);

    if (ProxyUtils.isLastChunk(httpObject)) {
        writeEmptyBuffer();
    }

    closeConnectionsAfterWriteIfNecessary(serverConnection,
            currentHttpRequest, currentHttpResponse, httpObject);
}
 
Example 5
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);
        }
    }
}