类 io.netty.handler.codec.http.DefaultFullHttpRequest 源码实例Demo

下面列出了怎么用 io.netty.handler.codec.http.DefaultFullHttpRequest 的API类实例代码及写法,或者点击链接到github查看源代码。

源代码1 项目: SI   文件: HttpClient.java

public boolean sendAsyncRequest(ResponseListener listener, String url, OneM2mRequest reqMessage) {
	
	try {
		URI uri = new URI(url);
		String host = uri.getHost() == null? "127.0.0.1" : uri.getHost();
		int port = uri.getPort();
		if(port == -1) port = 80;
		
		DefaultFullHttpRequest request = makeHttpMessage(host, reqMessage);

		log.debug("sendAsyncRequest");
		bootstrap.connect(host, port).addListener(new ConnectListner(request, mHttpClientListener, listener));
		
		return true;
		
	} catch (Exception e) {
		log.error("sendAsyncRequest", e);
	}
	
	return false;
}
 
源代码2 项目: serve   文件: TestUtils.java

public static void scaleModel(
        Channel channel, String modelName, String version, int minWorker, boolean sync) {
    String requestURL = "/models/" + modelName;

    if (version != null) {
        requestURL += "/" + version;
    }

    requestURL += "?min_worker=" + minWorker;

    if (sync) {
        requestURL += "&synchronous=true";
    }

    HttpRequest req =
            new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.PUT, requestURL);
    channel.writeAndFlush(req);
}
 

@Test
public void testNotNoHbaConfig() throws Exception {
    HttpAuthUpstreamHandler handler = new HttpAuthUpstreamHandler(Settings.EMPTY, authService);
    EmbeddedChannel ch = new EmbeddedChannel(handler);

    DefaultHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST, "/_sql");
    request.headers().add(HttpHeaderNames.AUTHORIZATION.toString(), "Basic QWxhZGRpbjpPcGVuU2VzYW1l");
    request.headers().add("X-Real-Ip", "10.1.0.100");

    ch.writeInbound(request);
    ch.releaseInbound();
    assertFalse(handler.authorized());

    assertUnauthorized(
        ch.readOutbound(),
        "No valid auth.host_based.config entry found for host \"10.1.0.100\", user \"Aladdin\", protocol \"http\"\n");
}
 
源代码4 项目: netty-4.1.22   文件: HttpProxyHandler.java

@Override
protected Object newInitialMessage(ChannelHandlerContext ctx) throws Exception {
    InetSocketAddress raddr = destinationAddress();
    final String host = NetUtil.toSocketAddressString(raddr);
    FullHttpRequest req = new DefaultFullHttpRequest(
            HttpVersion.HTTP_1_1, HttpMethod.CONNECT,
            host,
            Unpooled.EMPTY_BUFFER, false);

    req.headers().set(HttpHeaderNames.HOST, host);

    if (authorization != null) {
        req.headers().set(HttpHeaderNames.PROXY_AUTHORIZATION, authorization);
    }

    if (headers != null) {
        req.headers().add(headers);
    }

    return req;
}
 

@Test
public void assertChannelReadStartSuccess() {
    scalingConfiguration.getRuleConfiguration().setSourceDatasource("ds_0: !!" + YamlDataSourceConfiguration.class.getName() + "\n  "
            + "dataSourceClassName: com.zaxxer.hikari.HikariDataSource\n  props:\n    "
            + "jdbcUrl: jdbc:h2:mem:test_db;DB_CLOSE_DELAY=-1;DATABASE_TO_UPPER=false;MODE=MySQL\n    username: root\n    password: 'password'\n    connectionTimeout: 30000\n    "
            + "idleTimeout: 60000\n    maxLifetime: 1800000\n    maxPoolSize: 50\n    minPoolSize: 1\n    maintenanceIntervalMilliseconds: 30000\n    readOnly: false\n");
    scalingConfiguration.getRuleConfiguration().getDestinationDataSources().setUrl("jdbc:h2:mem:test_db;DB_CLOSE_DELAY=-1;DATABASE_TO_UPPER=false;MODE=MySQL");
    scalingConfiguration.getRuleConfiguration().getDestinationDataSources().setName("root");
    scalingConfiguration.getRuleConfiguration().getDestinationDataSources().setPassword("password");
    ByteBuf byteBuf = Unpooled.copiedBuffer(GSON.toJson(scalingConfiguration), CharsetUtil.UTF_8);
    fullHttpRequest = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST, "/scaling/job/start", byteBuf);
    httpServerHandler.channelRead0(channelHandlerContext, fullHttpRequest);
    ArgumentCaptor argumentCaptor = ArgumentCaptor.forClass(FullHttpResponse.class);
    verify(channelHandlerContext).writeAndFlush(argumentCaptor.capture());
    FullHttpResponse fullHttpResponse = (FullHttpResponse) argumentCaptor.getValue();
    assertTrue(fullHttpResponse.content().toString(CharsetUtil.UTF_8).contains("{\"success\":true"));
}
 

@Test
public void testNoSchemeRequestTargetHandled() throws Exception {
    bootstrapEnv(2, 1, 0);
    final FullHttpRequest request = new DefaultFullHttpRequest(HTTP_1_1, GET, "/");
    final HttpHeaders httpHeaders = request.headers();
    httpHeaders.setInt(HttpConversionUtil.ExtensionHeaderNames.STREAM_ID.text(), 5);
    httpHeaders.set(HttpHeaderNames.HOST, "localhost");
    ChannelPromise writePromise = newPromise();
    ChannelFuture writeFuture = clientChannel.writeAndFlush(request, writePromise);

    assertTrue(writePromise.awaitUninterruptibly(WAIT_TIME_SECONDS, SECONDS));
    assertTrue(writePromise.isDone());
    assertFalse(writePromise.isSuccess());
    assertTrue(writeFuture.isDone());
    assertFalse(writeFuture.isSuccess());
}
 
源代码7 项目: timely   文件: HttpRequestDecoderTest.java

@Test
public void testLookupPostWithLimit() throws Exception {
// @formatter:off
    String content =
    "{\n" +
    "    \"metric\": \"sys.cpu.user\",\n" +
    "    \"limit\": 3000\n" +
    "}";
    // @formatter:on
    decoder = new TestHttpQueryDecoder(config);
    DefaultFullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST,
            "/api/search/lookup");
    request.content().writeBytes(content.getBytes());
    addCookie(request);
    decoder.decode(null, request, results);
    Assert.assertEquals(1, results.size());
    Assert.assertEquals(SearchLookupRequest.class, results.iterator().next().getClass());
    SearchLookupRequest lookup = (SearchLookupRequest) results.iterator().next();
    Assert.assertEquals("sys.cpu.user", lookup.getQuery());
    Assert.assertEquals(3000, lookup.getLimit());
    Assert.assertEquals(0, lookup.getTags().size());
}
 

private void testPredictionsValidRequestSize(Channel channel) throws InterruptedException {
    result = null;
    latch = new CountDownLatch(1);
    DefaultFullHttpRequest req =
            new DefaultFullHttpRequest(
                    HttpVersion.HTTP_1_1, HttpMethod.POST, "/predictions/noop");

    req.content().writeZero(10385760);
    HttpUtil.setContentLength(req, req.content().readableBytes());
    req.headers().set(HttpHeaderNames.CONTENT_TYPE, HttpHeaderValues.APPLICATION_OCTET_STREAM);
    channel.writeAndFlush(req);

    latch.await();

    Assert.assertEquals(httpStatus, HttpResponseStatus.OK);
}
 
源代码9 项目: brpc-java   文件: HttpProtoProtocolTest.java

@Test
public void testDecodeHttpRequest() throws Exception {
    ServiceManager serviceManager = ServiceManager.getInstance();
    serviceManager.registerService(new EchoServiceImpl(), null);

    ByteBuf content = Unpooled.wrappedBuffer(encodeBody(
            Echo.EchoRequest.newBuilder().setMessage("hello").build()));

    FullHttpRequest httpRequest = new DefaultFullHttpRequest(HttpVersion.HTTP_1_0, HttpMethod.GET,
            "/example.EchoService/Echo", content);
    httpRequest.headers().set("log-id", 1);
    httpRequest.setUri("/example.EchoService/Echo");
    httpRequest.headers().set(HttpHeaderNames.CONTENT_TYPE, "application/proto; charset=utf-8");
    httpRequest.headers().set("key", "value");

    Request request = protocol.decodeRequest(httpRequest);
    assertEquals("example.EchoService", request.getRpcMethodInfo().getServiceName());
    assertEquals("Echo", request.getRpcMethodInfo().getMethodName());
    assertEquals(EchoService.class.getMethods()[0], request.getTargetMethod());
    assertEquals(EchoServiceImpl.class, request.getTarget().getClass());
    assertEquals(request.getKvAttachment().get("key"), "value");
}
 
源代码10 项目: tutorials   文件: EmbeddedChannelUnitTest.java

@Test
public void givenTwoChannelHandlers_testPipeline() {

	final FullHttpRequest httpRequest = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET,
			"/calculate?a=10&b=5");
	httpRequest.headers().add("Operator", "Add");

	EmbeddedChannel channel = new EmbeddedChannel(new HttpMessageHandler(), new CalculatorOperationHandler());

	channel.pipeline().addFirst(new HttpMessageHandler()).addLast(new CalculatorOperationHandler());

	// send HTTP request to server and check that the message is on the inbound pipeline
	assertThat(channel.writeInbound(httpRequest)).isTrue();

	long inboundChannelResponse = channel.readInbound();
	assertThat(inboundChannelResponse).isEqualTo(15);

	// we should have an outbound message in the form of a HTTP response
	assertThat(channel.outboundMessages().size()).isEqualTo(1);
	// Object response = channel.readOutbound();

	FullHttpResponse httpResponse = channel.readOutbound();
	String httpResponseContent = httpResponse.content().toString(Charset.defaultCharset());
	assertThat(httpResponseContent).isEqualTo("15");
}
 

private void testRegisterModelHttpError() throws InterruptedException {
    Channel channel = connect(true);
    Assert.assertNotNull(channel);

    HttpRequest req =
            new DefaultFullHttpRequest(
                    HttpVersion.HTTP_1_1,
                    HttpMethod.POST,
                    "/models?url=https%3A%2F%2Flocalhost%3A8443%2Ffake.mar&synchronous=false");
    channel.writeAndFlush(req).sync();
    channel.closeFuture().sync();

    ErrorResponse resp = JsonUtils.GSON.fromJson(result, ErrorResponse.class);

    Assert.assertEquals(resp.getCode(), HttpResponseStatus.BAD_REQUEST.code());
    Assert.assertEquals(
            resp.getMessage(),
            "Failed to download model from: https://localhost:8443/fake.mar, code: 404");
}
 

@Test
public void canHandleNettyCookies() {
    HttpRequest request = new DefaultFullHttpRequest(HTTP_1_1, GET, "http://foo.com/");
    request.headers().set(HOST, "http://foo.com/");
    request.headers().set("Cookie", "ABC01=\"1\"; ABC02=1; guid=xxxxx-xxx-xxx-xxx-xxxxxxx");

    NettyToStyxRequestDecoder decoder = new NettyToStyxRequestDecoder.Builder()
            .uniqueIdSupplier(uniqueIdSupplier)
            .build();

    LiveHttpRequest styxRequest = decoder.makeAStyxRequestFrom(request, Flux.empty())
            .build();

    LiveHttpRequest expected = new LiveHttpRequest.Builder(
            HttpMethod.GET, "http://foo.com/")
            .cookies(
                    requestCookie("ABC01", "\"1\""),
                    requestCookie("ABC02", "1"),
                    requestCookie("guid", "xxxxx-xxx-xxx-xxx-xxxxxxx")
            )
            .build();
    assertThat(newHashSet(styxRequest.cookies()), is(newHashSet(expected.cookies())));
}
 

@Test
public void testBindUnknownSession() throws Exception {
   EasyMock
      .expect(sessionDao.readSession("test"))
      .andThrow(new UnknownSessionException());
   replay();

   DefaultFullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, "http://localhost/client");
   DefaultHttpHeaders.addHeader(request, "Cookie", "irisAuthToken=test;");
   handler.channelRead(context, request);
   
   
   // an authenticated Client should have been bound
   ClientFactory factory = ServiceLocator.getInstance(ClientFactory.class);
   Client client = factory.get(channel);
   assertNotNull(client);
   assertFalse(client.isAuthenticated());
   assertEquals(null, client.getSessionId());

   verify();
}
 
源代码14 项目: serve   文件: ModelServerTest.java

@Test(
        alwaysRun = true,
        dependsOnMethods = {"testRegisterModelMalformedUrl"})
public void testRegisterModelConnectionFailed() throws InterruptedException {
    Channel channel = TestUtils.connect(true, configManager);
    Assert.assertNotNull(channel);

    HttpRequest req =
            new DefaultFullHttpRequest(
                    HttpVersion.HTTP_1_1,
                    HttpMethod.POST,
                    "/models?url=http%3A%2F%2Flocalhost%3A18888%2Ffake.mar&synchronous=false");
    channel.writeAndFlush(req).sync();
    channel.closeFuture().sync();

    ErrorResponse resp = JsonUtils.GSON.fromJson(TestUtils.getResult(), ErrorResponse.class);

    Assert.assertEquals(resp.getCode(), HttpResponseStatus.BAD_REQUEST.code());
    Assert.assertEquals(
            resp.getMessage(),
            "Failed to download model from: http://localhost:18888/fake.mar");
}
 
源代码15 项目: tutorials   文件: EmbeddedChannelUnitTest.java

@Test
public void givenTwoChannelHandlers_testExceptionHandlingInCalculatorOperationHandler() {
	EmbeddedChannel channel = new EmbeddedChannel(new HttpMessageHandler(), new CalculatorOperationHandler());

	final FullHttpRequest wrongHttpRequest = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET,
			"/calculate?a=10&b=5");
	wrongHttpRequest.headers().add("Operator", "Invalid_operation");

	// the HttpMessageHandler does not handle the exception and throws it down the pipeline
       assertThatThrownBy(() -> {
           channel.writeInbound(wrongHttpRequest);
       }).isInstanceOf(IllegalArgumentException.class)
         .hasMessage("Operation not defined");

	// the outbound message is a HTTP response with the status code 500
	FullHttpResponse errorHttpResponse = channel.readOutbound();
	String errorHttpResponseContent = errorHttpResponse.content().toString(Charset.defaultCharset());
	assertThat(errorHttpResponseContent).isEqualToIgnoringCase("Operation not defined");
	assertThat(errorHttpResponse.status()).isEqualTo(HttpResponseStatus.INTERNAL_SERVER_ERROR);
}
 

@Test
public void testHandoffInvalidToken() throws Exception {
   EasyMock
      .expect(appHandoffDao.validate("token"))
      .andReturn(Optional.empty());
   
   replay();
   
   DefaultFullHttpRequest request = new DefaultFullHttpRequest(
         HttpVersion.HTTP_1_1, 
         HttpMethod.POST, 
         "http://localhost/client",
         Unpooled.wrappedBuffer("{token:\"token\"}".getBytes("UTF-8"))
   );
   
   FullHttpResponse response = authenticator.authenticateRequest(channel, request);
   assertEquals(HttpResponseStatus.UNAUTHORIZED, response.getStatus());
   assertCookieCleared(response);
   
   verify();
}
 

private FullHttpResponse login(String email, String password, ChannelHandlerContext ctx) throws Exception {
   FullHttpRequest fakeLogin = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST, "/login");
   fakeLogin.headers().add(HttpHeaders.Names.CONTENT_TYPE, "application/x-www-form-urlencoded");

   String params = new StringBuilder("password=")
      .append(URLEncoder.encode(password, CharsetUtil.UTF_8.name()))
      .append("&")
      .append("user=")
      .append(URLEncoder.encode(email, CharsetUtil.UTF_8.name()))
      .toString();

   ByteBuf buffer = Unpooled.copiedBuffer(params, CharsetUtil.UTF_8);

   fakeLogin.headers().add(HttpHeaders.Names.CONTENT_LENGTH, buffer.readableBytes());
   fakeLogin.content().clear().writeBytes(buffer);
   return authenticator.authenticateRequest(ctx.channel(), fakeLogin);
}
 
源代码18 项目: timely   文件: HttpRequestDecoderTest.java

@Test
public void testSuggestPostWithValidTypeAndQuery() throws Exception {
// @formatter:off
    String content =
    "{\n" +
    "    \"type\": \"metrics\",\n" +
    "    \"q\": \"sys.cpu.user\"\n" +
    "}";
    // @formatter:on
    decoder = new TestHttpQueryDecoder(config);
    DefaultFullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST,
            "/api/suggest");
    request.content().writeBytes(content.getBytes());
    addCookie(request);
    decoder.decode(null, request, results);
    Assert.assertEquals(1, results.size());
    Assert.assertEquals(SuggestRequest.class, results.iterator().next().getClass());
    SuggestRequest suggest = (SuggestRequest) results.iterator().next();
    Assert.assertEquals("metrics", suggest.getType());
    Assert.assertEquals("sys.cpu.user", suggest.getQuery().get());
    Assert.assertEquals(25, suggest.getMax());
    suggest.validate();
}
 

@Test
public void testEncodeEmptyFullRequestWithTrailers() throws Exception {
    EmbeddedChannel ch = new EmbeddedChannel(new Http2StreamFrameToHttpObjectCodec(false));
    FullHttpRequest request = new DefaultFullHttpRequest(
            HttpVersion.HTTP_1_1, HttpMethod.PUT, "/hello/world");

    HttpHeaders trailers = request.trailingHeaders();
    trailers.set("key", "value");
    assertTrue(ch.writeOutbound(request));

    Http2HeadersFrame headersFrame = ch.readOutbound();
    Http2Headers headers = headersFrame.headers();

    assertThat(headers.scheme().toString(), is("http"));
    assertThat(headers.method().toString(), is("PUT"));
    assertThat(headers.path().toString(), is("/hello/world"));
    assertFalse(headersFrame.isEndStream());

    Http2HeadersFrame trailersFrame = ch.readOutbound();
    assertThat(trailersFrame.headers().get("key").toString(), is("value"));
    assertTrue(trailersFrame.isEndStream());

    assertThat(ch.readOutbound(), is(nullValue()));
    assertFalse(ch.finish());
}
 
源代码20 项目: styx   文件: HttpMessageSupport.java

public static HttpRequest httpRequest(HttpMethod method, String url, String body) {
    ByteBuf content = Unpooled.copiedBuffer(body.getBytes(Charset.forName("US-ASCII")));
    HttpRequest request = new DefaultFullHttpRequest(HTTP_1_1,
            method,
            url,
            content);
    HttpHeaders.setContentLength(request, content.writerIndex());
    return request;
}
 

@Test
public void testHttpPostRequestEncoderSlicedBuffer() throws Exception {
    DefaultFullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1,
            HttpMethod.POST, "http://localhost");

    HttpPostRequestEncoder encoder = new HttpPostRequestEncoder(request, true);
    // add Form attribute
    encoder.addBodyAttribute("getform", "POST");
    encoder.addBodyAttribute("info", "first value");
    encoder.addBodyAttribute("secondinfo", "secondvalue a&");
    encoder.addBodyAttribute("thirdinfo", "short text");
    int length = 100000;
    char[] array = new char[length];
    Arrays.fill(array, 'a');
    String longText = new String(array);
    encoder.addBodyAttribute("fourthinfo", longText.substring(0, 7470));
    File file1 = new File(getClass().getResource("/file-01.txt").toURI());
    encoder.addBodyFileUpload("myfile", file1, "application/x-zip-compressed", false);
    encoder.finalizeRequest();
    while (! encoder.isEndOfInput()) {
        HttpContent httpContent = encoder.readChunk((ByteBufAllocator) null);
        ByteBuf content = httpContent.content();
        int refCnt = content.refCnt();
        assertTrue("content: " + content + " content.unwrap(): " + content.unwrap() + " refCnt: " + refCnt,
                (content.unwrap() == content || content.unwrap() == null) && refCnt == 1 ||
                content.unwrap() != content && refCnt == 2);
        httpContent.release();
    }
    encoder.cleanFiles();
    encoder.close();
}
 
源代码22 项目: ambry   文件: NettyMultipartRequestTest.java

/**
 * Gets the encoded size for a set of bytes
 * @param bytes the bytes to encode.
 * @return the encoded size
 * @throws Exception
 */
private int getEncodedSize(byte[] bytes) throws Exception {
  int encodedSize = 0;
  InMemoryFile[] files = {new InMemoryFile(RestUtils.MultipartPost.BLOB_PART, ByteBuffer.wrap(bytes))};
  HttpRequest httpRequest = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST, "/");
  HttpPostRequestEncoder encoder = createEncoder(httpRequest, files);
  encoder.finalizeRequest();
  while (!encoder.isEndOfInput()) {
    HttpContent httpContent = encoder.readChunk(PooledByteBufAllocator.DEFAULT);
    encodedSize += httpContent.content().readableBytes();
  }
  return encodedSize;
}
 

@Test
public void testFullHttpRequestUpload() throws Exception {
    final String boundary = "dLV9Wyq26L_-JQxk6ferf-RT153LhOO";

    final DefaultFullHttpRequest req = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST,
            "http://localhost");

    req.setDecoderResult(DecoderResult.SUCCESS);
    req.headers().add(HttpHeaderNames.CONTENT_TYPE, "multipart/form-data; boundary=" + boundary);
    req.headers().add(HttpHeaderNames.TRANSFER_ENCODING, HttpHeaderValues.CHUNKED);

    // Force to use memory-based data.
    final DefaultHttpDataFactory inMemoryFactory = new DefaultHttpDataFactory(false);

    for (String data : Arrays.asList("", "\r", "\r\r", "\r\r\r")) {
        final String body =
                "--" + boundary + "\r\n" +
                        "Content-Disposition: form-data; name=\"file\"; filename=\"tmp-0.txt\"\r\n" +
                        "Content-Type: image/gif\r\n" +
                        "\r\n" +
                        data + "\r\n" +
                        "--" + boundary + "--\r\n";

        req.content().writeBytes(body.getBytes(CharsetUtil.UTF_8));
    }
    // Create decoder instance to test.
    final HttpPostRequestDecoder decoder = new HttpPostRequestDecoder(inMemoryFactory, req);
    assertFalse(decoder.getBodyHttpDatas().isEmpty());
    decoder.destroy();
}
 

private void testInvalidManagementUri() throws InterruptedException {
    Channel channel = connect(true);
    Assert.assertNotNull(channel);

    HttpRequest req =
            new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, "/InvalidUrl");
    channel.writeAndFlush(req).sync();
    channel.closeFuture().sync();

    ErrorResponse resp = JsonUtils.GSON.fromJson(result, ErrorResponse.class);

    Assert.assertEquals(resp.getCode(), HttpResponseStatus.NOT_FOUND.code());
    Assert.assertEquals(resp.getMessage(), ERROR_NOT_FOUND);
}
 
源代码25 项目: arcusplatform   文件: TestBearerAuth.java

@Test
public void testIsAuthorizedNoPersonMatchesToken() {
   EasyMock.expect(oauthDao.getPersonWithAccess("app1", "foobar")).andReturn(null);
   replay();

   DefaultFullHttpRequest req = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST, "http://localhost");
   req.headers().add(HttpHeaders.AUTHORIZATION, "Bearer foobar");

   assertFalse(auth.isAuthorized(null, req));
}
 
源代码26 项目: hadoop   文件: SimpleHttpProxyHandler.java

@Override
public void channelRead0
  (final ChannelHandlerContext ctx, final HttpRequest req) {
  uri = req.getUri();
  final Channel client = ctx.channel();
  Bootstrap proxiedServer = new Bootstrap()
    .group(client.eventLoop())
    .channel(NioSocketChannel.class)
    .handler(new ChannelInitializer<SocketChannel>() {
      @Override
      protected void initChannel(SocketChannel ch) throws Exception {
        ChannelPipeline p = ch.pipeline();
        p.addLast(new HttpRequestEncoder(), new Forwarder(uri, client));
      }
    });
  ChannelFuture f = proxiedServer.connect(host);
  proxiedChannel = f.channel();
  f.addListener(new ChannelFutureListener() {
    @Override
    public void operationComplete(ChannelFuture future) throws Exception {
      if (future.isSuccess()) {
        ctx.channel().pipeline().remove(HttpResponseEncoder.class);
        HttpRequest newReq = new DefaultFullHttpRequest(HTTP_1_1,
          req.getMethod(), req.getUri());
        newReq.headers().add(req.headers());
        newReq.headers().set(CONNECTION, Values.CLOSE);
        future.channel().writeAndFlush(newReq);
      } else {
        DefaultHttpResponse resp = new DefaultHttpResponse(HTTP_1_1,
          INTERNAL_SERVER_ERROR);
        resp.headers().set(CONNECTION, Values.CLOSE);
        LOG.info("Proxy " + uri + " failed. Cause: ", future.cause());
        ctx.writeAndFlush(resp).addListener(ChannelFutureListener.CLOSE);
        client.close();
      }
    }
  });
}
 
源代码27 项目: sofa-rpc   文件: Http2ClientInitializer.java

@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
    DefaultFullHttpRequest upgradeRequest = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET,
        "/");
    ctx.writeAndFlush(upgradeRequest);

    ctx.fireChannelActive();

    // Done with this handler, remove it from the pipeline.
    ctx.pipeline().remove(this);

    configureEndOfPipeline(ctx.pipeline());
}
 
源代码28 项目: blueflood   文件: HandlerTestsBase.java

private FullHttpRequest createRequest(HttpMethod method, String uri, String requestBody) {
    DefaultFullHttpRequest rawRequest = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, method, uri);
    rawRequest.headers().set("tenantId", TENANT);
    if (!requestBody.equals(""))
        rawRequest.content().writeBytes(Unpooled.copiedBuffer(requestBody.getBytes()));
    return HttpRequestWithDecodedQueryParams.create(rawRequest);
}
 

private void testInvalidModelMethod() throws InterruptedException {
    Channel channel = connect(true);
    Assert.assertNotNull(channel);

    HttpRequest req =
            new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST, "/models/noop");
    channel.writeAndFlush(req).sync();
    channel.closeFuture().sync();

    ErrorResponse resp = JsonUtils.GSON.fromJson(result, ErrorResponse.class);

    Assert.assertEquals(resp.getCode(), HttpResponseStatus.METHOD_NOT_ALLOWED.code());
    Assert.assertEquals(resp.getMessage(), ERROR_METHOD_NOT_ALLOWED);
}
 
源代码30 项目: timely   文件: HttpRequestDecoderTest.java

@Test(expected = IllegalArgumentException.class)
public void testSuggestNoSession() throws Exception {
    decoder = new TestHttpQueryDecoder(config);
    DefaultFullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET,
            "/api/suggest?type=foo");
    decoder.decode(null, request, results);
}
 
 同包方法