Search in sources :

Example 71 with DefaultLastHttpContent

use of io.netty.handler.codec.http.DefaultLastHttpContent in project zuul by Netflix.

the class ZuulMessageImplTest method testBufferBody3GetBodyAsText.

@Test
public void testBufferBody3GetBodyAsText() {
    final ZuulMessage msg = new ZuulMessageImpl(new SessionContext(), new Headers());
    msg.bufferBodyContents(new DefaultHttpContent(Unpooled.copiedBuffer("Hello ".getBytes())));
    msg.bufferBodyContents(new DefaultHttpContent(Unpooled.copiedBuffer("World!".getBytes())));
    msg.bufferBodyContents(new DefaultLastHttpContent());
    final String body = msg.getBodyAsText();
    assertTrue(msg.hasBody());
    assertTrue(msg.hasCompleteBody());
    assertEquals("Hello World!", body);
    assertEquals(0, msg.getHeaders().getAll("Content-Length").size());
}
Also used : DefaultLastHttpContent(io.netty.handler.codec.http.DefaultLastHttpContent) DefaultHttpContent(io.netty.handler.codec.http.DefaultHttpContent) SessionContext(com.netflix.zuul.context.SessionContext) Test(org.junit.Test)

Example 72 with DefaultLastHttpContent

use of io.netty.handler.codec.http.DefaultLastHttpContent in project zuul by Netflix.

the class ProxyEndpoint method buildZuulHttpResponse.

private HttpResponseMessage buildZuulHttpResponse(final HttpResponse httpResponse, final StatusCategory statusCategory, final Throwable ex) {
    startedSendingResponseToClient = true;
    // Translate the netty HttpResponse into a zuul HttpResponseMessage.
    final SessionContext zuulCtx = context;
    final int respStatus = httpResponse.status().code();
    final HttpResponseMessage zuulResponse = new HttpResponseMessageImpl(zuulCtx, zuulRequest, respStatus);
    final Headers respHeaders = zuulResponse.getHeaders();
    for (Map.Entry<String, String> entry : httpResponse.headers()) {
        respHeaders.add(entry.getKey(), entry.getValue());
    }
    // a LastHttpContent without any prior HttpContent's.
    if (HttpUtils.hasChunkedTransferEncodingHeader(zuulResponse) || HttpUtils.hasNonZeroContentLengthHeader(zuulResponse)) {
        zuulResponse.setHasBody(true);
    }
    // Store this original response info for future reference (ie. for metrics and access logging purposes).
    zuulResponse.storeInboundResponse();
    channelCtx.channel().attr(ATTR_ZUUL_RESP).set(zuulResponse);
    if (httpResponse instanceof DefaultFullHttpResponse) {
        final ByteBuf chunk = ((DefaultFullHttpResponse) httpResponse).content();
        zuulResponse.bufferBodyContents(new DefaultLastHttpContent(chunk));
    }
    // Request was a success even if server may have responded with an error code 5XX, except for 503.
    if (originConn != null) {
        if (statusCategory == ZuulStatusCategory.FAILURE_ORIGIN_THROTTLED) {
            origin.onRequestExecutionFailed(zuulRequest, originConn.getServer(), attemptNum, new ClientException(ClientException.ErrorType.SERVER_THROTTLED));
        } else {
            origin.onRequestExecutionSuccess(zuulRequest, zuulResponse, originConn.getServer(), attemptNum);
        }
    }
    // Collect some info about the received response.
    origin.recordFinalResponse(zuulResponse);
    origin.recordFinalError(zuulRequest, ex);
    zuulCtx.put(CommonContextKeys.STATUS_CATGEORY, statusCategory);
    zuulCtx.setError(ex);
    zuulCtx.put("origin_http_status", Integer.toString(respStatus));
    return transformResponse(zuulResponse);
}
Also used : DefaultFullHttpResponse(io.netty.handler.codec.http.DefaultFullHttpResponse) HttpResponseMessage(com.netflix.zuul.message.http.HttpResponseMessage) DefaultLastHttpContent(io.netty.handler.codec.http.DefaultLastHttpContent) Headers(com.netflix.zuul.message.Headers) HttpResponseMessageImpl(com.netflix.zuul.message.http.HttpResponseMessageImpl) SessionContext(com.netflix.zuul.context.SessionContext) ClientException(com.netflix.client.ClientException) ByteBuf(io.netty.buffer.ByteBuf) Map(java.util.Map) HashMap(java.util.HashMap)

Example 73 with DefaultLastHttpContent

use of io.netty.handler.codec.http.DefaultLastHttpContent in project proxyee-down by monkeyWie.

the class SniffIntercept method afterResponse.

@Override
public void afterResponse(Channel clientChannel, Channel proxyChannel, HttpResponse httpResponse, HttpProxyInterceptPipeline pipeline) throws Exception {
    if (!matchFlag) {
        super.afterResponse(clientChannel, proxyChannel, httpResponse, pipeline);
        return;
    }
    if ((httpResponse.status().code() + "").indexOf("20") == 0) {
        // 响应码为20x
        HttpHeaders httpResHeaders = httpResponse.headers();
        String accept = pipeline.getHttpRequest().headers().get(HttpHeaderNames.ACCEPT);
        String contentType = httpResHeaders.get(HttpHeaderNames.CONTENT_TYPE);
        // 有两种情况进行下载 1.url后缀为.xxx  2.带有CONTENT_DISPOSITION:ATTACHMENT响应头
        String disposition = httpResHeaders.get(HttpHeaderNames.CONTENT_DISPOSITION);
        if (accept != null && accept.matches("^.*text/html.*$") && ((disposition != null && disposition.contains(HttpHeaderValues.ATTACHMENT) && disposition.contains(HttpHeaderValues.FILENAME)) || isDownContentType(contentType))) {
            downFlag = true;
        }
        HttpRequestInfo httpRequestInfo = (HttpRequestInfo) pipeline.getHttpRequest();
        if (downFlag) {
            // 如果是下载
            LOGGER.debug("=====================下载===========================\n" + pipeline.getHttpRequest().toString() + "\n" + "------------------------------------------------" + httpResponse.toString() + "\n" + "================================================");
            // 关闭嗅探下载连接
            proxyChannel.close();
            httpRequestInfo.setRequestProto(new RequestProto(pipeline.getRequestProto().getHost(), pipeline.getRequestProto().getPort(), pipeline.getRequestProto().getSsl()));
            HttpRequestForm requestForm = HttpRequestForm.parse(httpRequestInfo);
            HttpResponseInfo responseInfo = HttpDownUtil.getHttpResponseInfo(httpRequestInfo, null, null, (NioEventLoopGroup) clientChannel.eventLoop().parent());
            httpResponse.headers().clear();
            httpResponse.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/html");
            httpResponse.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderValues.CLOSE);
            String js = "<script type=\"text/javascript\">window.history.go(-1)</script>";
            HttpContent httpContent = new DefaultLastHttpContent();
            httpContent.content().writeBytes(js.getBytes());
            httpResponse.headers().set(HttpHeaderNames.CONTENT_LENGTH, httpContent.content().readableBytes());
            clientChannel.writeAndFlush(httpResponse);
            clientChannel.writeAndFlush(httpContent);
            clientChannel.close();
            ObjectMapper objectMapper = new ObjectMapper();
            String requestParam = URLEncoder.encode(objectMapper.writeValueAsString(requestForm), "utf-8");
            String responseParam = URLEncoder.encode(objectMapper.writeValueAsString(responseInfo), "utf-8");
            String uri = "/#/tasks?request=" + requestParam + "&response=" + responseParam;
            DownApplication.INSTANCE.loadUri(uri, false);
            return;
        } else {
            if (httpRequestInfo.content() != null) {
                httpRequestInfo.setContent(null);
            }
        }
    }
    super.afterResponse(clientChannel, proxyChannel, httpResponse, pipeline);
}
Also used : HttpHeaders(io.netty.handler.codec.http.HttpHeaders) HttpResponseInfo(org.pdown.core.entity.HttpResponseInfo) DefaultLastHttpContent(io.netty.handler.codec.http.DefaultLastHttpContent) HttpRequestForm(org.pdown.rest.form.HttpRequestForm) HttpRequestInfo(org.pdown.core.entity.HttpRequestInfo) RequestProto(org.pdown.core.util.ProtoUtil.RequestProto) LastHttpContent(io.netty.handler.codec.http.LastHttpContent) HttpContent(io.netty.handler.codec.http.HttpContent) DefaultLastHttpContent(io.netty.handler.codec.http.DefaultLastHttpContent) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper)

Aggregations

DefaultLastHttpContent (io.netty.handler.codec.http.DefaultLastHttpContent)73 LastHttpContent (io.netty.handler.codec.http.LastHttpContent)32 Test (org.junit.Test)27 ByteBuf (io.netty.buffer.ByteBuf)26 DefaultHttpContent (io.netty.handler.codec.http.DefaultHttpContent)26 EmbeddedChannel (io.netty.channel.embedded.EmbeddedChannel)24 HttpContent (io.netty.handler.codec.http.HttpContent)17 HttpHeaders (io.netty.handler.codec.http.HttpHeaders)12 HttpRequest (io.netty.handler.codec.http.HttpRequest)12 DefaultHttpRequest (io.netty.handler.codec.http.DefaultHttpRequest)11 HttpResponse (io.netty.handler.codec.http.HttpResponse)11 DefaultHttpResponse (io.netty.handler.codec.http.DefaultHttpResponse)10 Test (org.junit.jupiter.api.Test)10 DefaultFullHttpRequest (io.netty.handler.codec.http.DefaultFullHttpRequest)9 FullHttpRequest (io.netty.handler.codec.http.FullHttpRequest)7 Channel (io.netty.channel.Channel)6 Test (org.testng.annotations.Test)6 SessionContext (com.netflix.zuul.context.SessionContext)5 JsonObjectDecoder (io.netty.handler.codec.json.JsonObjectDecoder)5 ByteArrayOutputStream (java.io.ByteArrayOutputStream)5