当前位置: 首页>>代码示例>>Java>>正文


Java DefaultHttpHeaders类代码示例

本文整理汇总了Java中io.netty.handler.codec.http.DefaultHttpHeaders的典型用法代码示例。如果您正苦于以下问题:Java DefaultHttpHeaders类的具体用法?Java DefaultHttpHeaders怎么用?Java DefaultHttpHeaders使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。


DefaultHttpHeaders类属于io.netty.handler.codec.http包,在下文中一共展示了DefaultHttpHeaders类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: fixHandlerBeforeConnect

import io.netty.handler.codec.http.DefaultHttpHeaders; //导入依赖的package包/类
/**
	 * 适配
	 */
	@Override
	protected ChannelHandler fixHandlerBeforeConnect(final ChannelHandler handler) {
		ChannelHandler result=new ShareableChannelInboundHandler() {
			@Override
			public void channelRegistered(ChannelHandlerContext ctx) throws Exception {
				Channel ch=ctx.channel();
				ch.pipeline().addLast(new HttpClientCodec());
            	ch.pipeline().addLast(new HttpObjectAggregator(64*1024));
            	ch.pipeline().addLast(new WebSocketClientProtocolHandler(WebSocketClientHandshakerFactory.newHandshaker(uri, WebSocketVersion.V13, null, false, new DefaultHttpHeaders())));
            	ch.pipeline().addLast(new WebSocketConnectedClientHandler(handler));
				ctx.pipeline().remove(this);//移除当前handler
				ctx.pipeline().fireChannelRegistered();//重新从第一个handler抛出事件
			}
		};
//		ChannelInitializer<SocketChannel> result=new ChannelInitializer<SocketChannel>() {
//            @Override
//            protected void initChannel(SocketChannel ch) {
//            	ch.pipeline().addLast(new HttpClientCodec());
//            	ch.pipeline().addLast(new HttpObjectAggregator(64*1024));
//            	ch.pipeline().addLast(new WebSocketClientProtocolHandler(WebSocketClientHandshakerFactory.newHandshaker(uri, WebSocketVersion.V13, null, false, new DefaultHttpHeaders())));
//            	ch.pipeline().addLast(new WebSocketConnectedClientHandler(handler));
//            }
//        };
        return result;
	}
 
开发者ID:juebanlin,项目名称:util4j,代码行数:29,代码来源:NettyTextWebSocketClient.java

示例2: fixHandlerBeforeConnect

import io.netty.handler.codec.http.DefaultHttpHeaders; //导入依赖的package包/类
/**
	 * 适配
	 */
	@Override
	protected ChannelHandler fixHandlerBeforeConnect(final ChannelHandler handler) {
		ChannelHandler result=new ShareableChannelInboundHandler() {
			@Override
			public void channelRegistered(ChannelHandlerContext ctx) throws Exception {
				Channel ch=ctx.channel();
				ch.pipeline().addLast(new HttpClientCodec());
            	ch.pipeline().addLast(new HttpObjectAggregator(64*1024));
            	ch.pipeline().addLast(new WebSocketClientProtocolHandler(WebSocketClientHandshakerFactory.newHandshaker(uri, WebSocketVersion.V13, null, false, new DefaultHttpHeaders())));
            	ch.pipeline().addLast(new WebSocketConnectedClientHandler(handler));
				ctx.pipeline().remove(this);//移除当前handler
				ctx.fireChannelRegistered();//重新从第一个handler抛出事件
			}
		};
//		ChannelInitializer<SocketChannel> result=new ChannelInitializer<SocketChannel>() {
//            @Override
//            protected void initChannel(SocketChannel ch) {
//            	ch.pipeline().addLast(new HttpClientCodec());
//            	ch.pipeline().addLast(new HttpObjectAggregator(64*1024));
//            	ch.pipeline().addLast(new WebSocketClientProtocolHandler(WebSocketClientHandshakerFactory.newHandshaker(uri, WebSocketVersion.V13, null, false, new DefaultHttpHeaders())));
//            	ch.pipeline().addLast(new WebSocketConnectedClientHandler(handler));
//            }
//        };
        return result;
	}
 
开发者ID:juebanlin,项目名称:util4j,代码行数:29,代码来源:NettyBinaryWebSocketClient.java

示例3: testConvert

import io.netty.handler.codec.http.DefaultHttpHeaders; //导入依赖的package包/类
@Test
public void testConvert() throws IOException {
    Response responseMock = mock(Response.class);

    HttpHeaders headers = new DefaultHttpHeaders();
    headers.add(TEST_KEY_A, TEST_VALUE_B);
    headers.add(TEST_KEY_C, TEST_VALUE_D);

    when(responseMock.getHeaders()).thenReturn(headers);
    when(responseMock.getStatusCode()).thenReturn(STATUS_CODE);
    when(responseMock.getStatusText()).thenReturn(STATUS_TEXT);
    when(responseMock.getResponseBodyAsStream()).thenReturn(
            new ByteArrayInputStream(ENCODED_BODY.getBytes(StandardCharsets.UTF_8))
    );

    BiFunction<Response, Request, HttpResponse> converter = new AsyncResponseConverter();
    HttpResponse awsResponse = converter.apply(responseMock, null);

    assertThat(awsResponse.getHeaders().get(TEST_KEY_A)).isEqualTo(TEST_VALUE_B);
    assertThat(awsResponse.getHeaders().get(TEST_KEY_C)).isEqualTo(TEST_VALUE_D);
    assertThat(awsResponse.getStatusCode()).isEqualTo(STATUS_CODE);
    assertThat(awsResponse.getStatusText()).isEqualTo(STATUS_TEXT);
    assertThat(new BufferedReader(new InputStreamReader(awsResponse.getContent())).readLine())
            .isEqualTo(ENCODED_BODY);
}
 
开发者ID:Bandwidth,项目名称:async-sqs,代码行数:26,代码来源:AsyncResponseConverterTest.java

示例4: execute

import io.netty.handler.codec.http.DefaultHttpHeaders; //导入依赖的package包/类
@Override
public CompletableFuture<ResponseInfo<byte[]>> execute(RequestInfo<Void> request,
                                                       Executor longRunningTaskExecutor,
                                                       ChannelHandlerContext ctx) {
    /* Redirect requests from '/dashboard' to '/dashboard/'
         Without this redirect, assets would be requested with URI '/asset.ext' instead of '/dashboard/asset.ext'.
         This is important because the '/dashboard' prefix is needed in order to match this endpoint.
    */
    if (StringUtils.endsWith(request.getPath(), DASHBOARD_ENDPOINT_NO_TRAILING_SLASH)) {
        return CompletableFuture.completedFuture(
                ResponseInfo.<byte[]>newBuilder()
                        .withHttpStatusCode(HttpResponseStatus.MOVED_PERMANENTLY.code())
                        .withHeaders(new DefaultHttpHeaders().add(HttpHeaders.LOCATION, DASHBOARD_ENDPOINT))
                        .build());
    } else if (StringUtils.endsWith(request.getPath(), VERSION_FILE_NAME)) {
        String versionJson = String.format(VERSION_RESPONSE_FORMAT, cmsVersion);
        return CompletableFuture.completedFuture(
                ResponseInfo.<byte[]>newBuilder()
                        .withDesiredContentWriterMimeType("application/json")
                        .withContentForFullResponse(versionJson.getBytes(Charset.defaultCharset()))
                        .withHttpStatusCode(HttpResponseStatus.OK.code())
                        .build());
    } else {
        return CompletableFuture.completedFuture(getDashboardAsset(request));
    }
}
 
开发者ID:Nike-Inc,项目名称:cerberus-management-service,代码行数:27,代码来源:GetDashboard.java

示例5: test_validateSecureRequestForEndpoint_adds_security_context_to_request

import io.netty.handler.codec.http.DefaultHttpHeaders; //导入依赖的package包/类
@Test
public void test_validateSecureRequestForEndpoint_adds_security_context_to_request() {
    final RequestInfo<Void> requestInfo = mock(RequestInfo.class);
    when(requestInfo.getUri()).thenReturn("https://localhost");
    final HttpHeaders httpHeaders = new DefaultHttpHeaders();
    httpHeaders.add(CmsRequestSecurityValidator.HEADER_X_VAULT_TOKEN, vaultToken);
    when(requestInfo.getHeaders()).thenReturn(httpHeaders);

    final Map<String, String> meta = Maps.newHashMap();
    meta.put(VaultAuthPrincipal.METADATA_KEY_IS_ADMIN, Boolean.TRUE.toString());
    meta.put(VaultAuthPrincipal.METADATA_KEY_USERNAME, "username");
    meta.put(VaultAuthPrincipal.METADATA_KEY_GROUPS, "group1,group2");
    final VaultClientTokenResponse clientTokenResponse = new VaultClientTokenResponse()
            .setId(vaultToken)
            .setMeta(meta);
    when(vaultAdminClient.lookupToken(vaultToken)).thenReturn(clientTokenResponse);

    subject.validateSecureRequestForEndpoint(requestInfo, securedEndpoint);

    verify(requestInfo).addRequestAttribute(eq(SECURITY_CONTEXT_ATTR_KEY), any(SecurityContext.class));
}
 
开发者ID:Nike-Inc,项目名称:cerberus-management-service,代码行数:22,代码来源:CmsRequestSecurityValidatorTest.java

示例6: execute_throws_api_error_when_bad_auth_header

import io.netty.handler.codec.http.DefaultHttpHeaders; //导入依赖的package包/类
@Test
public void execute_throws_api_error_when_bad_auth_header() {
    final RequestInfo<Void> requestInfo = mock(RequestInfo.class);
    final HttpHeaders httpHeaders = new DefaultHttpHeaders();
    httpHeaders.add(HttpHeaders.Names.AUTHORIZATION, invalidAuthorizationHeader);
    when(requestInfo.getHeaders()).thenReturn(httpHeaders);

    try {
        final CompletableFuture<ResponseInfo<AuthResponse>> completableFuture =
                subject.execute(requestInfo, executor, null);
        completableFuture.join();
        fail("Expected exception not thrown.");
    } catch (CompletionException cex) {
        assertThat(cex.getCause()).isInstanceOf(ApiException.class);
    }
}
 
开发者ID:Nike-Inc,项目名称:cerberus-management-service,代码行数:17,代码来源:AuthenticateUserTest.java

示例7: initChannel

import io.netty.handler.codec.http.DefaultHttpHeaders; //导入依赖的package包/类
@Override
protected void initChannel(SocketChannel channel) throws SSLException {
    URI uri = config.getConnectionWebsocketUri();

    DefaultHttpHeaders headers = new DefaultHttpHeaders();
    headers.add(USER_ID_HEADER, config.getConnectionUserId().toString());
    headers.add(USER_PASSWORD_HEADER, config.getConnectionUserPassword());
    headers.add(SUPPLIER_ID_HEADER, config.getConnectionServerId());

    WebSocketClientHandshaker handshaker = WebSocketClientHandshakerFactory.newHandshaker(uri, WS_VERSION, null, false, headers);

    ChannelPipeline pipeline = channel.pipeline();
    if (config.isConnectionSecure()) {
        try {
            SslContext sslContext = SslContext.newClientContext(InsecureTrustManagerFactory.INSTANCE);
            pipeline.addLast(sslContext.newHandler(channel.alloc()));
        } catch (SSLException e) {
            logger.log(Level.SEVERE, "Shutting down client due to unexpected failure to create SSL context", e);
            throw e;
        }
    }
    pipeline.addLast(new HttpClientCodec());
    pipeline.addLast(new HttpObjectAggregator(8192));
    pipeline.addLast(new AudioConnectClientHandler(handshaker));
}
 
开发者ID:DeadmanDungeons,项目名称:AudioConnect,代码行数:26,代码来源:AudioConnectClient.java

示例8: mock

import io.netty.handler.codec.http.DefaultHttpHeaders; //导入依赖的package包/类
@Test
public void doChannelRead_creates_and_sets_RequestInfo_on_state_and_RequestInfo_is_marked_as_complete_with_all_chunks_if_msg_is_FullHttpRequest() {
    // given
    FullHttpRequest msgMock = mock(FullHttpRequest.class);
    String uri = "/some/url";
    HttpHeaders headers = new DefaultHttpHeaders();
    doReturn(uri).when(msgMock).getUri();
    doReturn(headers).when(msgMock).headers();
    doReturn(headers).when(msgMock).trailingHeaders();
    doReturn(byteBufMock).when(msgMock).content();
    doReturn(false).when(byteBufMock).isReadable();
    doReturn(HttpVersion.HTTP_1_1).when(msgMock).getProtocolVersion();

    // when
    PipelineContinuationBehavior result = handler.doChannelRead(ctxMock, msgMock);

    // then
    ArgumentCaptor<RequestInfo> requestInfoArgumentCaptor = ArgumentCaptor.forClass(RequestInfo.class);
    verify(stateMock).setRequestInfo(requestInfoArgumentCaptor.capture());
    RequestInfo requestInfo = requestInfoArgumentCaptor.getValue();
    assertThat(requestInfo.getUri()).isEqualTo(uri);
    assertThat(requestInfo.isCompleteRequestWithAllChunks()).isTrue();
    assertThat(result).isEqualTo(PipelineContinuationBehavior.CONTINUE);
}
 
开发者ID:Nike-Inc,项目名称:riposte,代码行数:25,代码来源:RequestInfoSetterHandlerTest.java

示例9: beforeMethod

import io.netty.handler.codec.http.DefaultHttpHeaders; //导入依赖的package包/类
@Before
public void beforeMethod() {
    stateMock = mock(HttpProcessingState.class);
    ctxMock = mock(ChannelHandlerContext.class);
    channelMock = mock(Channel.class);
    stateAttrMock = mock(Attribute.class);
    requestInfoMock = mock(RequestInfo.class);
    endpointMock = mock(StandardEndpoint.class);
    matcherMock = mock(Matcher.class);
    endpoints = new ArrayList<>(Collections.singleton(endpointMock));
    httpHeaders = new DefaultHttpHeaders();
    maxRequestSizeInBytes = 10;
    msg = mock(HttpRequest.class);

    doReturn(channelMock).when(ctxMock).channel();
    doReturn(stateAttrMock).when(channelMock).attr(ChannelAttributes.HTTP_PROCESSING_STATE_ATTRIBUTE_KEY);
    doReturn(stateMock).when(stateAttrMock).get();
    doReturn(endpointMock).when(stateMock).getEndpointForExecution();
    doReturn(matcherMock).when(endpointMock).requestMatcher();
    doReturn(Optional.of(defaultPath)).when(matcherMock).matchesPath(any(RequestInfo.class));
    doReturn(true).when(matcherMock).matchesMethod(any(RequestInfo.class));
    doReturn(requestInfoMock).when(stateMock).getRequestInfo();
    doReturn(httpHeaders).when(msg).headers();

    handlerSpy = spy(new RoutingHandler(endpoints, maxRequestSizeInBytes));
}
 
开发者ID:Nike-Inc,项目名称:riposte,代码行数:27,代码来源:RoutingHandlerTest.java

示例10: getHeaderMapDelegatesToRequestInfoAndCachesResult

import io.netty.handler.codec.http.DefaultHttpHeaders; //导入依赖的package包/类
@Test
public void getHeaderMapDelegatesToRequestInfoAndCachesResult() {
    Map<String, List<String>> expectedHeaderMap = new TreeMap<>(MapBuilder.<String, List<String>>builder()
                                                                          .put("header1", Arrays.asList("h1val1"))
                                                                          .put("header2", Arrays.asList("h2val1", "h2val2"))
                                                                          .build());

    HttpHeaders nettyHeaders = new DefaultHttpHeaders();
    for (Map.Entry<String, List<String>> headerEntry : expectedHeaderMap.entrySet()) {
        nettyHeaders.add(headerEntry.getKey(), headerEntry.getValue());
    }
    setFieldOnRequestInfo("headers", nettyHeaders);
    Map<String, List<String>> actualHeaderMap = adapter.getHeadersMap();
    assertThat(actualHeaderMap, is(expectedHeaderMap));
    assertThat(adapter.getHeadersMap(), sameInstance(actualHeaderMap));
}
 
开发者ID:Nike-Inc,项目名称:riposte,代码行数:17,代码来源:RequestInfoForLoggingRiposteAdapterTest.java

示例11: uber_constructor_for_full_response_sets_fields_as_expected

import io.netty.handler.codec.http.DefaultHttpHeaders; //导入依赖的package包/类
@Test
public void uber_constructor_for_full_response_sets_fields_as_expected() {
    // given
    int httpStatusCode = 200;
    HttpHeaders headers = new DefaultHttpHeaders();
    String mimeType = "text/text";
    Charset contentCharset = CharsetUtil.UTF_8;
    Set<Cookie> cookies = Sets.newHashSet(new DefaultCookie("key1", "val1"), new DefaultCookie("key2", "val2"));
    boolean preventCompressedResponse = true;

    // when
    BaseResponseInfo<?> responseInfo = createNewBaseResponseInfoForTesting(httpStatusCode, headers, mimeType, contentCharset, cookies, preventCompressedResponse);

    // then
    assertThat(responseInfo.getHttpStatusCode(), is(httpStatusCode));
    assertThat(responseInfo.getHeaders(), is(headers));
    assertThat(responseInfo.getDesiredContentWriterMimeType(), is(mimeType));
    assertThat(responseInfo.getDesiredContentWriterEncoding(), is(contentCharset));
    assertThat(responseInfo.getCookies(), is(cookies));
    assertThat(responseInfo.getUncompressedRawContentLength(), nullValue());
    assertThat(responseInfo.isPreventCompressedOutput(), is(preventCompressedResponse));
    assertThat(responseInfo.isResponseSendingStarted(), is(false));
    assertThat(responseInfo.isResponseSendingLastChunkSent(), is(false));
}
 
开发者ID:Nike-Inc,项目名称:riposte,代码行数:25,代码来源:BaseResponseInfoTest.java

示例12: determineCharsetFromContentType_works

import io.netty.handler.codec.http.DefaultHttpHeaders; //导入依赖的package包/类
@Test
@DataProvider(value = {
        "text/text charset=US-ASCII |   UTF-8   | US-ASCII",
        "text/text charset=us-ascii |   UTF-8   | US-ASCII",
        "text/text                  |   UTF-8   | UTF-8",
        "                           |   UTF-8   | UTF-8",
        "null                       |   UTF-8   | UTF-8",
}, splitBy = "\\|")
public void determineCharsetFromContentType_works(String contentTypeHeader, String defaultCharsetString, String expectedCharsetString) {
    // given
    Charset defaultCharset = Charset.forName(defaultCharsetString);
    Charset expectedCharset = Charset.forName(expectedCharsetString);
    HttpHeaders headers = new DefaultHttpHeaders().add(HttpHeaders.Names.CONTENT_TYPE, String.valueOf(contentTypeHeader));

    // when
    Charset actualCharset = HttpUtils.determineCharsetFromContentType(headers, defaultCharset);

    // then
    assertThat(actualCharset, is(expectedCharset));
}
 
开发者ID:Nike-Inc,项目名称:riposte,代码行数:21,代码来源:HttpUtilsTest.java

示例13: extractCookies_works_if_cookies_defined_in_headers

import io.netty.handler.codec.http.DefaultHttpHeaders; //导入依赖的package包/类
@Test
public void extractCookies_works_if_cookies_defined_in_headers() {
    // given
    Cookie cookie1 = new DefaultCookie(UUID.randomUUID().toString(), UUID.randomUUID().toString());
    Cookie cookie2 = new DefaultCookie(UUID.randomUUID().toString(), UUID.randomUUID().toString());
    HttpHeaders headers = new DefaultHttpHeaders().add(HttpHeaders.Names.COOKIE, ClientCookieEncoder.LAX.encode(cookie1, cookie2));

    HttpRequest nettyRequestMock = mock(HttpRequest.class);
    doReturn(headers).when(nettyRequestMock).headers();

    // when
    Set<Cookie> extractedCookies = HttpUtils.extractCookies(nettyRequestMock);

    // then
    assertThat(extractedCookies.contains(cookie1), is(true));
    assertThat(extractedCookies.contains(cookie2), is(true));
}
 
开发者ID:Nike-Inc,项目名称:riposte,代码行数:18,代码来源:HttpUtilsTest.java

示例14: extractCookies_works_if_cookies_defined_in_trailing_headers

import io.netty.handler.codec.http.DefaultHttpHeaders; //导入依赖的package包/类
@Test
public void extractCookies_works_if_cookies_defined_in_trailing_headers() {
    // given
    Cookie cookie1 = new DefaultCookie(UUID.randomUUID().toString(), UUID.randomUUID().toString());
    Cookie cookie2 = new DefaultCookie(UUID.randomUUID().toString(), UUID.randomUUID().toString());
    HttpHeaders trailingHeaders = new DefaultHttpHeaders().add(HttpHeaders.Names.COOKIE, ClientCookieEncoder.LAX.encode(cookie1, cookie2));

    FullHttpRequest nettyRequestMock = mock(FullHttpRequest.class);
    doReturn(new DefaultHttpHeaders()).when(nettyRequestMock).headers();
    doReturn(trailingHeaders).when(nettyRequestMock).trailingHeaders();

    // when
    Set<Cookie> extractedCookies = HttpUtils.extractCookies(nettyRequestMock);

    // then
    assertThat(extractedCookies.contains(cookie1), is(true));
    assertThat(extractedCookies.contains(cookie2), is(true));
}
 
开发者ID:Nike-Inc,项目名称:riposte,代码行数:19,代码来源:HttpUtilsTest.java

示例15: extractCookies_handles_cookie_values_leniently

import io.netty.handler.codec.http.DefaultHttpHeaders; //导入依赖的package包/类
@Test
public void extractCookies_handles_cookie_values_leniently() {
    // given
    //these are cookie values seen in the wild...
    Cookie cookie1 = new DefaultCookie(UUID.randomUUID().toString(), "2094%3Az%7C2021%3Ab");
    Cookie cookie2 = new DefaultCookie(UUID.randomUUID().toString(), "geoloc=cc=US,rc=OR,tp=vhigh,tz=PST,la=45.4978,lo=-122.6937,bw=5000");
    Cookie cookie3 = new DefaultCookie(UUID.randomUUID().toString(), "\"dm=n.com&si=27431295-a282-4745-8cd5-542e7fce" +
            "429e&ss=1477551008358&sl=76&tt=437632&obo=12&sh=1477552753923%3D76%3A12%3A437632%2C1477552698670%3D75%3" +
            "A12%3A429879%2C1477552677137%3D74%3A12%3A426596%2C1477552672564%3D73%3A12%3A425585%2C1477552669893%3D72" +
            "%3A12%3A423456&bcn=%2F%2F3408178b.mpstat.us%2F&ld=1477552753923&r=http%3A%2F%2Fwww.nike.com%2Fbe%2Fde_de%" +
            "2F&ul=1477552756811\"");
    HttpHeaders headers = new DefaultHttpHeaders().add(HttpHeaders.Names.COOKIE, ClientCookieEncoder.LAX.encode(cookie1, cookie2, cookie3));

    HttpRequest nettyRequestMock = mock(HttpRequest.class);
    doReturn(headers).when(nettyRequestMock).headers();

    // when
    Set<Cookie> extractedCookies = HttpUtils.extractCookies(nettyRequestMock);

    // then
    assertThat(extractedCookies.contains(cookie1), is(true));
    assertThat(extractedCookies.contains(cookie2), is(true));
    assertThat(extractedCookies.contains(cookie3), is(true));
}
 
开发者ID:Nike-Inc,项目名称:riposte,代码行数:25,代码来源:HttpUtilsTest.java


注:本文中的io.netty.handler.codec.http.DefaultHttpHeaders类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。