io.netty.handler.codec.http.HttpResponse Java Examples

The following examples show how to use io.netty.handler.codec.http.HttpResponse. 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: ClientRequestReceiver.java    From zuul with Apache License 2.0 6 votes vote down vote up
@Override
public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
    if (msg instanceof HttpResponse) {
        promise.addListener((future) -> {
            if (! future.isSuccess()) {
                fireWriteError("response headers", future.cause(), ctx);
            }
        });
        super.write(ctx, msg, promise);
    }
    else if (msg instanceof HttpContent) {
        promise.addListener((future) -> {
            if (! future.isSuccess())  {
                fireWriteError("response content", future.cause(), ctx);
            }
        });
        super.write(ctx, msg, promise);
    }
    else {
        //should never happen
        ReferenceCountUtil.release(msg);
        throw new ZuulException("Attempt to write invalid content type to client: "+msg.getClass().getSimpleName(), true);
    }
}
 
Example #2
Source File: HttpController.java    From litchi with Apache License 2.0 6 votes vote down vote up
public void writeFile(String fileName, String text) {
	ByteBuf content = Unpooled.copiedBuffer(text, CharsetUtil.UTF_8);
	HttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, content);
	response.headers().set("Pragma", "Pragma");
	response.headers().set("Expires", "0");
	response.headers().set("Cache-Control", "must-revalidate, post-check=0, pre-check=0");
	response.headers().set("Content-Type", "application/download");
	response.headers().set("Content-Disposition", "attachment;filename=" + fileName);
	response.headers().set("Content-Transfer-Encoding", "binary");
	
	if (enableCookies) {
		for (Map.Entry<String, Cookie> entry : cookieMaps.entrySet()) {
			response.headers().add(HttpHeaderNames.SET_COOKIE, ServerCookieEncoder.STRICT.encode(entry.getValue()));
		}
	}
	
	// 跨域支持
	response.headers().add("Access-Control-Allow-Origin", "*");
	response.headers().add("Access-Control-Allow-Methods", "POST");
	HttpUtil.setContentLength(response, content.readableBytes());
	channel.writeAndFlush(response); //.addListener(ChannelFutureListener.CLOSE);
}
 
Example #3
Source File: HttpClientInitHandler.java    From util4j with Apache License 2.0 6 votes vote down vote up
@Override
	protected void initChannel(SocketChannel ch) throws Exception {
		ChannelPipeline p = ch.pipeline();
		if(sslCtx!=null)
		{
			p.addLast(new SslHandler(sslCtx.newEngine(ch.alloc())));
		}
		p.addLast(new HttpResponseDecoder());
		//限制contentLength
		p.addLast(new HttpObjectAggregator(65536));
		p.addLast(new HttpRequestEncoder());
		//大文件传输处理
//		p.addLast(new ChunkedWriteHandler());
		if(unPoolMsg)
		{
			p.addLast(new DefaultListenerHandler<HttpResponse>(new HttpListenerProxy(listener)));
		}else
		{
			p.addLast(new DefaultListenerHandler<HttpResponse>(listener));
		}
	}
 
Example #4
Source File: ConfigHandlerTest.java    From couchbase-jvm-core with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldDecodeSuccessBucketConfigResponse() throws Exception {
    HttpResponse responseHeader = new DefaultHttpResponse(HttpVersion.HTTP_1_1, new HttpResponseStatus(200, "OK"));
    HttpContent responseChunk1 = new DefaultHttpContent(Unpooled.copiedBuffer("foo", CHARSET));
    HttpContent responseChunk2 = new DefaultLastHttpContent(Unpooled.copiedBuffer("bar", CHARSET));

    BucketConfigRequest requestMock = mock(BucketConfigRequest.class);
    requestQueue.add(requestMock);
    channel.writeInbound(responseHeader, responseChunk1, responseChunk2);
    channel.readInbound();

    assertEquals(1, eventSink.responseEvents().size());
    BucketConfigResponse event = (BucketConfigResponse) eventSink.responseEvents().get(0).getMessage();

    assertEquals(ResponseStatus.SUCCESS, event.status());
    assertEquals("foobar", event.config());
    assertTrue(requestQueue.isEmpty());
}
 
Example #5
Source File: RecordController.java    From flashback with BSD 2-Clause "Simplified" License 6 votes vote down vote up
@Override
public void handleReadFromServer(HttpObject httpObject) {
  if (httpObject instanceof HttpResponse) {
    _serverResponseBuilder = new RecordedHttpResponseBuilder((HttpResponse) httpObject);
  }

  try {
    if (httpObject instanceof HttpContent) {
      _serverResponseBuilder.appendHttpContent((HttpContent) httpObject);
    }

    if (httpObject instanceof LastHttpContent) {
      _sceneAccessLayer.record(_clientRequestBuilder.build(), _serverResponseBuilder.build());
    }
  } catch (IOException e) {
    throw new RuntimeException("HRFS: Failed to record HttpContent", e);
  }
}
 
Example #6
Source File: HandshakeHandler.java    From socketio with Apache License 2.0 6 votes vote down vote up
private void handshake(final ChannelHandlerContext ctx, final HttpRequest req, final QueryStringDecoder queryDecoder)
    throws IOException {
  // Generate session ID
  final String sessionId = UUID.randomUUID().toString();
  if (log.isDebugEnabled())
    log.debug("New sessionId: {} generated", sessionId);

  // Send handshake response
  final String handshakeMessage = getHandshakeMessage(sessionId, queryDecoder);

  ByteBuf content = PipelineUtils.copiedBuffer(ctx.alloc(), handshakeMessage);
  HttpResponse res = PipelineUtils.createHttpResponse(PipelineUtils.getOrigin(req), content, false);
  ChannelFuture f = ctx.writeAndFlush(res);
  f.addListener(ChannelFutureListener.CLOSE);
  if (log.isDebugEnabled())
    log.debug("Sent handshake response: {} to channel: {}", handshakeMessage, ctx.channel());
}
 
Example #7
Source File: HttpServerOperations.java    From reactor-netty with Apache License 2.0 6 votes vote down vote up
static void sendDecodingFailures(ChannelHandlerContext ctx, Throwable t, Object msg) {
	Throwable cause = t.getCause() != null ? t.getCause() : t;

	if (log.isDebugEnabled()) {
		log.debug(format(ctx.channel(), "Decoding failed: " + msg + " : "), cause);
	}

	ReferenceCountUtil.release(msg);

	HttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_0,
			cause instanceof TooLongFrameException ? HttpResponseStatus.REQUEST_ENTITY_TOO_LARGE:
			                                         HttpResponseStatus.BAD_REQUEST);
	response.headers()
	        .setInt(HttpHeaderNames.CONTENT_LENGTH, 0)
	        .set(HttpHeaderNames.CONNECTION, HttpHeaderValues.CLOSE);
	ctx.writeAndFlush(response)
	   .addListener(ChannelFutureListener.CLOSE);
}
 
Example #8
Source File: HarCaptureFilter.java    From AndroidHttpCapture with MIT License 6 votes vote down vote up
protected void captureResponse(HttpResponse httpResponse) {
    HarResponse response = new HarResponse(httpResponse.getStatus().code(), httpResponse.getStatus().reasonPhrase(), httpResponse.getProtocolVersion().text());
    harEntry.setResponse(response);

    captureResponseHeaderSize(httpResponse);

    captureResponseMimeType(httpResponse);

    if (dataToCapture.contains(CaptureType.RESPONSE_COOKIES)) {
        captureResponseCookies(httpResponse);
    }

    if (dataToCapture.contains(CaptureType.RESPONSE_HEADERS)) {
        captureResponseHeaders(httpResponse);
    }

    if (BrowserMobHttpUtil.isRedirect(httpResponse)) {
        captureRedirectUrl(httpResponse);
    }
}
 
Example #9
Source File: StreamServerGroupHandler.java    From IpCamera with Eclipse Public License 2.0 6 votes vote down vote up
private void sendSnapshotImage(ChannelHandlerContext ctx, String contentType) throws IOException {
    HttpResponse response = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK);
    if (ipCameraGroupHandler.cameraIndex >= ipCameraGroupHandler.cameraOrder.size()) {
        logger.debug("WARN: Openhab may still be starting, or all cameras in the group are OFFLINE.");
        return;
    }
    ipCameraGroupHandler.cameraOrder.get(ipCameraGroupHandler.cameraIndex).lockCurrentSnapshot.lock();
    ByteBuf snapshotData = Unpooled
            .copiedBuffer(ipCameraGroupHandler.cameraOrder.get(ipCameraGroupHandler.cameraIndex).currentSnapshot);
    ipCameraGroupHandler.cameraOrder.get(ipCameraGroupHandler.cameraIndex).lockCurrentSnapshot.unlock();
    response.headers().add(HttpHeaderNames.CONTENT_TYPE, contentType);
    response.headers().set(HttpHeaderNames.CACHE_CONTROL, HttpHeaderValues.NO_CACHE);
    response.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderValues.CLOSE);
    response.headers().add(HttpHeaderNames.CONTENT_LENGTH, snapshotData.readableBytes());
    response.headers().add("Access-Control-Allow-Origin", "*");
    response.headers().add("Access-Control-Expose-Headers", "*");
    ctx.channel().write(response);
    ctx.channel().write(snapshotData);
    ByteBuf footerBbuf = Unpooled.copiedBuffer("\r\n", 0, 2, StandardCharsets.UTF_8);
    ctx.channel().writeAndFlush(footerBbuf);
}
 
Example #10
Source File: ClientToProxyConnection.java    From g4proxy with Apache License 2.0 6 votes vote down vote up
/**
 * This method takes care of closing client to proxy and/or proxy to server
 * connections after finishing a write.
 */
private void closeConnectionsAfterWriteIfNecessary(
        ProxyToServerConnection serverConnection,
        HttpRequest currentHttpRequest, HttpResponse currentHttpResponse,
        HttpObject httpObject) {
    boolean closeServerConnection = shouldCloseServerConnection(
            currentHttpRequest, currentHttpResponse, httpObject);
    boolean closeClientConnection = shouldCloseClientConnection(
            currentHttpRequest, currentHttpResponse, httpObject);

    if (closeServerConnection) {
        LOG.debug("Closing remote connection after writing to client");
        serverConnection.disconnect();
    }

    if (closeClientConnection) {
        LOG.debug("Closing connection to client after writes");
        disconnect();
    }
}
 
Example #11
Source File: ResponseTextIntercept.java    From proxyee-down with Apache License 2.0 6 votes vote down vote up
@Override
public void afterResponse(Channel clientChannel, Channel proxyChannel, HttpResponse httpResponse,
    HttpProxyInterceptPipeline pipeline) throws Exception {
  if (match(httpResponse, pipeline)) {
    isMatch = true;
    //解压gzip响应
    if ("gzip".equalsIgnoreCase(httpResponse.headers().get(HttpHeaderNames.CONTENT_ENCODING))) {
      isGzip = true;
      pipeline.reset3();
      proxyChannel.pipeline().addAfter("httpCodec", "decompress", new HttpContentDecompressor());
      proxyChannel.pipeline().fireChannelRead(httpResponse);
    } else {
      if (isGzip) {
        httpResponse.headers().set(HttpHeaderNames.CONTENT_ENCODING, HttpHeaderValues.GZIP);
      }
      contentBuf = PooledByteBufAllocator.DEFAULT.buffer();
    }
    //直接调用默认拦截器,跳过下载拦截器
    pipeline.getDefault()
        .afterResponse(clientChannel, proxyChannel, httpResponse, pipeline);
  } else {
    isMatch = false;
    pipeline.afterResponse(clientChannel, proxyChannel, httpResponse);
  }
}
 
Example #12
Source File: ConfigHandlerTest.java    From couchbase-jvm-core with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldDecodeAuthFailureBucketConfigResponse() throws Exception {
    HttpResponse responseHeader = new DefaultHttpResponse(HttpVersion.HTTP_1_1,
        new HttpResponseStatus(401, "Unauthorized"));
    HttpContent responseChunk = LastHttpContent.EMPTY_LAST_CONTENT;

    BucketConfigRequest requestMock = mock(BucketConfigRequest.class);
    requestQueue.add(requestMock);
    channel.writeInbound(responseHeader, responseChunk);

    assertEquals(1, eventSink.responseEvents().size());
    BucketConfigResponse event = (BucketConfigResponse) eventSink.responseEvents().get(0).getMessage();

    assertEquals(ResponseStatus.ACCESS_ERROR, event.status());
    assertEquals("Unauthorized", event.config());
    assertTrue(requestQueue.isEmpty());
}
 
Example #13
Source File: BrokerServiceLookupTest.java    From pulsar with Apache License 2.0 6 votes vote down vote up
private AsyncHttpClient getHttpClient(String version) {
    DefaultAsyncHttpClientConfig.Builder confBuilder = new DefaultAsyncHttpClientConfig.Builder();
    confBuilder.setFollowRedirect(true);
    confBuilder.setUserAgent(version);
    confBuilder.setKeepAliveStrategy(new DefaultKeepAliveStrategy() {
        @Override
        public boolean keepAlive(InetSocketAddress remoteAddress, Request ahcRequest,
                                 HttpRequest request, HttpResponse response) {
            // Close connection upon a server error or per HTTP spec
            return (response.status().code() / 100 != 5)
                   && super.keepAlive(remoteAddress, ahcRequest, request, response);
        }
    });
    AsyncHttpClientConfig config = confBuilder.build();
    return new DefaultAsyncHttpClient(config);
}
 
Example #14
Source File: HttpStreamEncoder.java    From netty-http2 with Apache License 2.0 6 votes vote down vote up
private HttpHeadersFrame createHttpHeadersFrame(HttpResponse httpResponse)
        throws Exception {
    // Get the Stream-ID from the headers
    int streamId = HttpHeaders.getIntHeader(httpResponse, "X-SPDY-Stream-ID");
    httpResponse.headers().remove("X-SPDY-Stream-ID");

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

    HttpHeadersFrame httpHeadersFrame = new DefaultHttpHeadersFrame(streamId);

    // Unfold the first line of the response into name/value pairs
    httpHeadersFrame.headers().set(":status", httpResponse.getStatus().code());

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

    return httpHeadersFrame;
}
 
Example #15
Source File: HarCaptureFilter.java    From browserup-proxy with Apache License 2.0 6 votes vote down vote up
protected void captureResponse(HttpResponse httpResponse) {
    HarResponse response = new HarResponse();
    response.setStatus(httpResponse.status().code());
    response.setStatusText(httpResponse.status().reasonPhrase());
    response.setHttpVersion(httpResponse.protocolVersion().text());
    harEntry.setResponse(response);

    captureResponseHeaderSize(httpResponse);

    captureResponseMimeType(httpResponse);

    if (dataToCapture.contains(CaptureType.RESPONSE_COOKIES)) {
        captureResponseCookies(httpResponse);
    }

    if (dataToCapture.contains(CaptureType.RESPONSE_HEADERS)) {
        captureResponseHeaders(httpResponse);
    }

    if (BrowserUpHttpUtil.isRedirect(httpResponse)) {
        captureRedirectUrl(httpResponse);
    }
}
 
Example #16
Source File: NettyHttpClient.java    From util4j with Apache License 2.0 6 votes vote down vote up
/**
 * 异步请求
 * @param host
 * @param port
 * @param request
 * @param callback
 */
public void asyncRequest(String host,int port,HttpRequest request,final CallBack<HttpResponse> callback,long timeOut)
{
	synchronized (request) {
		final HttpListener listener=new HttpListener(request);
		final NettyClient client=new NettyClient(config,new InetSocketAddress(host, port),new HttpClientInitHandler(listener));
		client.start();
		if(callback!=null)
		{
			scheduExec.execute(new Runnable() {
				@Override
				public void run() {
					HttpResponse result=listener.waitResponse(timeOut);
					callback.call(result!=null,Optional.ofNullable(result));
					client.stop();
				}
			});
		}
	}
}
 
Example #17
Source File: NettyHttpClient.java    From util4j with Apache License 2.0 6 votes vote down vote up
/**
 * 同步请求
 * @param host
 * @param port
 * @param request
 * @param waiteTimeMills
 * @return 超时返回null
 */
public HttpResponse syncRequest(String host,int port,HttpRequest request,long waiteTimeMills)
{
	HttpResponse response=null;
	synchronized (request) {
		if(response==null)
		{
			HttpListener listener=new HttpListener(request);
			NettyClient client=new NettyClient(config,new InetSocketAddress(host, port),new HttpClientInitHandler(listener));
			client.start();
			response=listener.waitResponse(waiteTimeMills);//阻塞等待结果
			client.stop();
		}
	}
	return response;
}
 
Example #18
Source File: DeviceUtils.java    From AndroidHttpCapture with MIT License 6 votes vote down vote up
public static void changeResponseFilter(SysApplication sysApplication,final List<ResponseFilterRule> ruleList){
    if(ruleList == null){
        Log.e("~~~~","changeResponseFilter ruleList == null!");
        return;
    }

    sysApplication.proxy.addResponseFilter(new ResponseFilter() {
        @Override
        public void filterResponse(HttpResponse response, HttpMessageContents contents, HttpMessageInfo messageInfo) {
            for (ResponseFilterRule rule: ruleList) {
                if(rule.getEnable()) {
                    if (contents.isText() && messageInfo.getUrl().contains(rule.getUrl())) {
                        String originContent = contents.getTextContents();
                        if (originContent != null) {
                            contents.setTextContents(contents.getTextContents().replaceAll(
                                    rule.getReplaceRegex(), rule.getReplaceContent()));
                        }
                    }
                }
            }
        }
    });
}
 
Example #19
Source File: ProxyRouterEndpointExecutionHandler.java    From riposte with Apache License 2.0 6 votes vote down vote up
protected void logResponseFirstChunk(HttpResponse response) {
    if (logger.isDebugEnabled()) {
        runnableWithTracingAndMdc(
            () -> {
                StringBuilder sb = new StringBuilder();
                for (String headerName : response.headers().names()) {
                    if (sb.length() > 0)
                        sb.append(", ");
                    sb.append(headerName).append("=\"")
                      .append(String.join(",", response.headers().getAll(headerName))).append("\"");
                }
                logger.debug("STREAMING RESPONSE HEADERS: " + sb.toString());
                logger.debug("STREAMING RESPONSE HTTP STATUS: " + response.status().code());
                logger.debug("STREAMING RESPONSE PROTOCOL: " + response.protocolVersion().text());
            },
            ctx
        ).run();
    }
}
 
Example #20
Source File: IrisUpnpServer.java    From arcusplatform with Apache License 2.0 6 votes vote down vote up
private void handleResponse(@Nullable ChannelHandlerContext ctx, DatagramPacket packet) throws Exception {
   EmbeddedChannel http = new EmbeddedChannel(new HttpResponseDecoder());

   try {
      http.writeInbound(Unpooled.unreleasableBuffer(packet.content()));
      http.finish();

      while (true) {
         Object result = http.readInbound();
         if (result == null) {
            break;
         }

         if (result instanceof HttpResponse) {
            HttpResponse res = (HttpResponse)result;
            switch (res.getStatus().code()) {
            case 200: handleUpnpMsearchResponse(packet, res); break;
            default: log.debug("unknown upnp response: {}", res.getStatus().code()); break;
            }
         } 
      }
   } finally {
      http.finishAndReleaseAll();
   }
}
 
Example #21
Source File: NettyHttpConduit.java    From cxf with Apache License 2.0 6 votes vote down vote up
protected synchronized HttpResponse getHttpResponse() throws IOException {
    while (httpResponse == null) {
        if (exception == null) { //already have an exception, skip waiting
            try {
                wait(entity.getReceiveTimeout());
            } catch (InterruptedException e) {
                throw new IOException(e);
            }
        }
        if (httpResponse == null) {

            if (exception != null) {
                if (exception instanceof IOException) {
                    throw (IOException)exception;
                }
                if (exception instanceof RuntimeException) {
                    throw (RuntimeException)exception;
                }
                throw new IOException(exception);
            }

            throw new SocketTimeoutException("Read Timeout");
        }
    }
    return httpResponse;
}
 
Example #22
Source File: AutoBasicAuthFilter.java    From browserup-proxy with Apache License 2.0 6 votes vote down vote up
@Override
public HttpResponse clientToProxyRequest(HttpObject httpObject) {
    if (credentialsByHostname.isEmpty()) {
        return null;
    }

    if (httpObject instanceof HttpRequest) {
        HttpRequest httpRequest = (HttpRequest) httpObject;

        // providing authorization during a CONNECT is generally not useful
        if (ProxyUtils.isCONNECT(httpRequest)) {
            return null;
        }

        String hostname = getHost(httpRequest);

        // if there is an entry in the credentials map matching this hostname, add the credentials to the request
        String base64CredentialsForHostname = credentialsByHostname.get(hostname);
        if (base64CredentialsForHostname != null) {
            httpRequest.headers().add(HttpHeaderNames.AUTHORIZATION, "Basic " + base64CredentialsForHostname);
        }
    }

    return null;
}
 
Example #23
Source File: DefaultRiposteProxyRouterSpanNamingAndTaggingStrategyTest.java    From riposte with Apache License 2.0 6 votes vote down vote up
@Test
public void alternate_constructor_creates_instance_using_specified_wingtips_strategy_and_adapter() {
    // given
    HttpTagAndSpanNamingStrategy<HttpRequest, HttpResponse> wingtipsStrategyMock =
        mock(HttpTagAndSpanNamingStrategy.class);
    HttpTagAndSpanNamingAdapter<HttpRequest, HttpResponse> wingtipsAdapterMock =
        mock(HttpTagAndSpanNamingAdapter.class);

    // when
    DefaultRiposteProxyRouterSpanNamingAndTaggingStrategy instance =
        new DefaultRiposteProxyRouterSpanNamingAndTaggingStrategy(wingtipsStrategyMock, wingtipsAdapterMock);

    // then
    assertThat(instance.tagAndNamingStrategy).isSameAs(wingtipsStrategyMock);
    assertThat(instance.tagAndNamingAdapter).isSameAs(wingtipsAdapterMock);
}
 
Example #24
Source File: DefaultRiposteProxyRouterSpanNamingAndTaggingStrategy.java    From riposte with Apache License 2.0 6 votes vote down vote up
/**
 * Creates a new instance that uses the given arguments to do the work of span naming and tagging.
 *
 * @param tagAndNamingStrategy The {@link HttpTagAndSpanNamingStrategy} to use.
 * @param tagAndNamingAdapter The {@link HttpTagAndSpanNamingAdapter} to use.
 */
@SuppressWarnings("ConstantConditions")
public DefaultRiposteProxyRouterSpanNamingAndTaggingStrategy(
    @NotNull HttpTagAndSpanNamingStrategy<HttpRequest, HttpResponse> tagAndNamingStrategy,
    @NotNull HttpTagAndSpanNamingAdapter<HttpRequest, HttpResponse> tagAndNamingAdapter
) {
    if (tagAndNamingStrategy == null) {
        throw new IllegalArgumentException(
            "tagAndNamingStrategy cannot be null - if you really want no strategy, use NoOpHttpTagStrategy"
        );
    }

    if (tagAndNamingAdapter == null) {
        throw new IllegalArgumentException(
            "tagAndNamingAdapter cannot be null - if you really want no adapter, use NoOpHttpTagAdapter"
        );
    }

    this.tagAndNamingStrategy = tagAndNamingStrategy;
    this.tagAndNamingAdapter = tagAndNamingAdapter;
}
 
Example #25
Source File: HttpUploadClientHandler.java    From netty-4.1.22 with Apache License 2.0 5 votes vote down vote up
@Override
public void channelRead0(ChannelHandlerContext ctx, HttpObject msg) {
    if (msg instanceof HttpResponse) {
        HttpResponse response = (HttpResponse) msg;

        System.err.println("STATUS: " + response.status());
        System.err.println("VERSION: " + response.protocolVersion());

        if (!response.headers().isEmpty()) {
            for (CharSequence name : response.headers().names()) {
                for (CharSequence value : response.headers().getAll(name)) {
                    System.err.println("HEADER: " + name + " = " + value);
                }
            }
        }

        if (response.status().code() == 200 && HttpUtil.isTransferEncodingChunked(response)) {
            readingChunks = true;
            System.err.println("CHUNKED CONTENT {");
        } else {
            System.err.println("CONTENT {");
        }
    }
    if (msg instanceof HttpContent) {
        HttpContent chunk = (HttpContent) msg;
        System.err.println(chunk.content().toString(CharsetUtil.UTF_8));

        if (chunk instanceof LastHttpContent) {
            if (readingChunks) {
                System.err.println("} END OF CHUNKED CONTENT");
            } else {
                System.err.println("} END OF CONTENT");
            }
            readingChunks = false;
        } else {
            System.err.println(chunk.content().toString(CharsetUtil.UTF_8));
        }
    }
}
 
Example #26
Source File: ProxyToServerConnection.java    From yfs with Apache License 2.0 5 votes vote down vote up
@Override
protected ConnectionState readHTTPInitial(HttpResponse httpResponse) {
    LOG.debug("Received raw response: {}", httpResponse);

    if (httpResponse.getDecoderResult().isFailure()) {
        LOG.debug("Could not parse response from server. Decoder result: {}", httpResponse.getDecoderResult().toString());

        // create a "substitute" Bad Gateway response from the server, since we couldn't understand what the actual
        // response from the server was. set the keep-alive on the substitute response to false so the proxy closes
        // the connection to the server, since we don't know what state the server thinks the connection is in.
        FullHttpResponse substituteResponse = ProxyUtils.createFullHttpResponse(HttpVersion.HTTP_1_1,
                HttpResponseStatus.BAD_GATEWAY,
                "Unable to parse response from server");
        HttpHeaders.setKeepAlive(substituteResponse, false);
        httpResponse = substituteResponse;
    }

    currentFilters.serverToProxyResponseReceiving();

    rememberCurrentResponse(httpResponse);
    respondWith(httpResponse);

    if (ProxyUtils.isChunked(httpResponse)) {
        return AWAITING_CHUNK;
    } else {
        currentFilters.serverToProxyResponseReceived();

        return AWAITING_INITIAL;
    }
}
 
Example #27
Source File: RequestsToOriginMetricsCollectorTest.java    From styx with Apache License 2.0 5 votes vote down vote up
@Test
public void updateSuccessCountersWhen200OkReceived() throws Exception {
    RequestsToOriginMetricsCollector handler = new RequestsToOriginMetricsCollector(this.originMetrics);
    HttpResponse msg = mockHttpResponseWithCode(200);
    handler.channelRead(this.ctx, msg);

    assertThat(this.metricRegistry.meter(name(APP_METRIC_PREFIX, REQUEST_SUCCESS)).getCount(), is(1L));
    assertThat(this.metricRegistry.meter(name(ORIGIN_METRIC_PREFIX, REQUEST_SUCCESS)).getCount(), is(1L));
}
 
Example #28
Source File: HttpSnoopClientHandler.java    From netty-4.1.22 with Apache License 2.0 5 votes vote down vote up
@Override
public void channelRead0(ChannelHandlerContext ctx, HttpObject msg) {
    if (msg instanceof HttpResponse) {
        HttpResponse response = (HttpResponse) msg;

        System.err.println("STATUS: " + response.status());
        System.err.println("VERSION: " + response.protocolVersion());
        System.err.println();

        if (!response.headers().isEmpty()) {
            for (CharSequence name: response.headers().names()) {
                for (CharSequence value: response.headers().getAll(name)) {
                    System.err.println("HEADER: " + name + " = " + value);
                }
            }
            System.err.println();
        }

        if (HttpUtil.isTransferEncodingChunked(response)) {
            System.err.println("CHUNKED CONTENT {");
        } else {
            System.err.println("CONTENT {");
        }
    }
    if (msg instanceof HttpContent) {
        HttpContent content = (HttpContent) msg;

        System.err.print(content.content().toString(CharsetUtil.UTF_8));
        System.err.flush();

        if (content instanceof LastHttpContent) {
            System.err.println("} END OF CONTENT");
            ctx.close();
        }
    }
}
 
Example #29
Source File: CorsHandlerTest.java    From netty4.0.27Learn with Apache License 2.0 5 votes vote down vote up
@Test
public void preflightRequestWithNullOrigin() {
    final String origin = "null";
    final CorsConfig config = CorsConfig.withOrigin(origin)
            .allowNullOrigin()
            .allowCredentials()
            .build();
    final HttpResponse response = preflightRequest(config, origin, "content-type, xheader1");
    assertThat(response.headers().get(ACCESS_CONTROL_ALLOW_ORIGIN), is(equalTo("*")));
    assertThat(response.headers().get(ACCESS_CONTROL_ALLOW_CREDENTIALS), is(nullValue()));
}
 
Example #30
Source File: HarCaptureFilter.java    From Dream-Catcher with MIT License 5 votes vote down vote up
protected void captureResponseCookies(HttpResponse httpResponse) {
    Log.e("InnerHandle", "captureResponseCookies " + harEntry.getId());
    List<String> setCookieHeaders = httpResponse.headers().getAll(HttpHeaders.Names.SET_COOKIE);
    if (setCookieHeaders == null) {
        return;
    }

    for (String setCookieHeader : setCookieHeaders) {
        Cookie cookie = ClientCookieDecoder.LAX.decode(setCookieHeader);
        if (cookie == null) {
            return;
        }

        HarCookie harCookie = new HarCookie();

        harCookie.setName(cookie.name());
        harCookie.setValue(cookie.value());
        // comment is no longer supported in the netty ClientCookieDecoder
        harCookie.setDomain(cookie.domain());
        harCookie.setHttpOnly(cookie.isHttpOnly());
        harCookie.setPath(cookie.path());
        harCookie.setSecure(cookie.isSecure());
        if (cookie.maxAge() > 0) {
            // use a Calendar with the current timestamp + maxAge seconds. the locale of the calendar is irrelevant,
            // since we are dealing with timestamps.
            Calendar expires = Calendar.getInstance();
            // zero out the milliseconds, since maxAge is in seconds
            expires.set(Calendar.MILLISECOND, 0);
            // we can't use Calendar.add, since that only takes ints. TimeUnit.convert handles second->millisecond
            // overflow reasonably well by returning the result as Long.MAX_VALUE.
            expires.setTimeInMillis(expires.getTimeInMillis() + TimeUnit.MILLISECONDS.convert(cookie.maxAge(), TimeUnit.SECONDS));

            harCookie.setExpires(expires.getTime());
        }

        harResponse.getResponse().getCookies().add(harCookie);
        harResponse.addHeader(harCookie.getName(), harCookie.getValue());
    }
}