Java 类io.netty.handler.codec.http.cookie.ClientCookieEncoder 实例源码

项目:riposte    文件:HttpUtilsTest.java   
@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));
}
项目:riposte    文件:HttpUtilsTest.java   
@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));
}
项目:riposte    文件:HttpUtilsTest.java   
@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));
}
项目:lannister    文件:HttpResponse.java   
public static HttpResponse createServerDefault(String requestCookie) {
    HttpResponse ret = new HttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, Unpooled.buffer());

    ret.headers().set(HttpHeaderNames.CONTENT_TYPE, "application/json; charset=UTF-8");

    if (requestCookie == null) { return ret; }

    Set<Cookie> cookies = ServerCookieDecoder.STRICT.decode(requestCookie);
    if (cookies.isEmpty()) { return ret; }

    // Reset the cookies if necessary.
    for (Cookie cookie : cookies) {
        ret.headers().add(HttpHeaderNames.SET_COOKIE, ClientCookieEncoder.STRICT.encode(cookie));
    }

    return ret;
}
项目:nomulus    文件:TestUtils.java   
public static FullHttpRequest makeEppHttpRequest(
    String content,
    String host,
    String path,
    String accessToken,
    String sslClientCertificateHash,
    String serverHostname,
    String clientAddress,
    Cookie... cookies) {
  FullHttpRequest request = makeHttpPostRequest(content, host, path);
  request
      .headers()
      .set(HttpHeaderNames.AUTHORIZATION, "Bearer " + accessToken)
      .set(HttpHeaderNames.CONTENT_TYPE, EPP_CONTENT_TYPE)
      .set(HttpHeaderNames.ACCEPT, EPP_CONTENT_TYPE)
      .set(SSL_CLIENT_CERTIFICATE_HASH_FIELD, sslClientCertificateHash)
      .set(REQUESTED_SERVERNAME_VIA_SNI_FIELD, serverHostname)
      .set(FORWARDED_FOR_FIELD, clientAddress);
  if (cookies.length != 0) {
    request.headers().set(HttpHeaderNames.COOKIE, ClientCookieEncoder.STRICT.encode(cookies));
  }
  return request;
}
项目:GameServerFramework    文件:NHttpRequestParams.java   
private void buildRequestHeaders(DefaultFullHttpRequest request) {
    // config request header
    request.headers().set(HttpHeaders.Names.HOST, this.uri.getHost());
    // 添加压缩头
    request.headers().set(HttpHeaders.Names.ACCEPT_ENCODING, "gzip, deflate");
    // added user agent
    if (userAgent != null && !userAgent.isEmpty()) request.headers().set(HttpHeaders.Names.USER_AGENT, userAgent);
    else request.headers().remove(HttpHeaders.Names.USER_AGENT);
    // add custom
    if (this.headers != null) {
        for (Entry<String, String> item : this.headers.entrySet()) {
            request.headers().set(item.getKey(), item.getValue());
        }
    }
    // add cookie
    if (this.cookies != null) {
        String cookieValue = ClientCookieEncoder.STRICT.encode(cookies);
        request.headers().set(HttpHeaders.Names.COOKIE, cookieValue);
    }
}
项目:divconq    文件:DownloadHandler.java   
public void start(final HyperSession parent, WritableByteChannel dest, String chanid, Map<String, Cookie> cookies, long size, long offset, final OperationCallback callback) {
    this.dest = dest;
    this.cookies = cookies;
    this.callback = callback;
    this.size = size;
    this.sent = offset;

    this.src = this.allocateChannel(parent, callback);

    if (this.callback.hasErrors()) {
        callback.complete();
        return;
    }

    // send a request to get things going

    HttpRequest req = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, "/download/" + chanid);

    req.headers().set(Names.HOST, parent.getInfo().getHost());
    req.headers().set(Names.USER_AGENT, "DivConq HyperAPI Client 1.0");
    req.headers().set(Names.CONNECTION, HttpHeaders.Values.CLOSE);
       req.headers().set(Names.COOKIE, ClientCookieEncoder.STRICT.encode(this.cookies.values()));

       // send request
       this.src.writeAndFlush(req);
}
项目:qonduit    文件:WebSocketIT.java   
@Before
public void setup() throws Exception {
    s = new Server(conf);
    s.run();

    Connector con = mac.getConnector("root", "secret");
    con.securityOperations().changeUserAuthorizations("root", new Authorizations("A", "B", "C", "D", "E", "F"));

    this.sessionId = UUID.randomUUID().toString();
    AuthCache.getCache().put(sessionId, token);
    group = new NioEventLoopGroup();
    SslContext ssl = SslContextBuilder.forClient().trustManager(InsecureTrustManagerFactory.INSTANCE).build();

    String cookieVal = ClientCookieEncoder.STRICT.encode(Constants.COOKIE_NAME, sessionId);
    HttpHeaders headers = new DefaultHttpHeaders();
    headers.add(Names.COOKIE, cookieVal);

    WebSocketClientHandshaker handshaker = WebSocketClientHandshakerFactory.newHandshaker(LOCATION,
            WebSocketVersion.V13, (String) null, false, headers);
    handler = new ClientHandler(handshaker);
    Bootstrap boot = new Bootstrap();
    boot.group(group).channel(NioSocketChannel.class).handler(new ChannelInitializer<SocketChannel>() {

        @Override
        protected void initChannel(SocketChannel ch) throws Exception {
            ch.pipeline().addLast("ssl", ssl.newHandler(ch.alloc(), "127.0.0.1", WS_PORT));
            ch.pipeline().addLast(new HttpClientCodec());
            ch.pipeline().addLast(new HttpObjectAggregator(8192));
            ch.pipeline().addLast(handler);
        }
    });
    ch = boot.connect("127.0.0.1", WS_PORT).sync().channel();
    // Wait until handshake is complete
    while (!handshaker.isHandshakeComplete()) {
        sleepUninterruptibly(500, TimeUnit.MILLISECONDS);
        LOG.debug("Waiting for Handshake to complete");
    }
}
项目:timely    文件:WebSocketIT.java   
@Before
public void setup() throws Exception {
    s = new Server(conf);
    s.run();

    Connector con = mac.getConnector("root", "secret");
    con.securityOperations().changeUserAuthorizations("root", new Authorizations("A", "B", "C", "D", "E", "F"));

    this.sessionId = UUID.randomUUID().toString();
    AuthCache.getCache().put(sessionId, token);
    group = new NioEventLoopGroup();
    SslContext ssl = SslContextBuilder.forClient().trustManager(InsecureTrustManagerFactory.INSTANCE).build();

    String cookieVal = ClientCookieEncoder.STRICT.encode(Constants.COOKIE_NAME, sessionId);
    HttpHeaders headers = new DefaultHttpHeaders();
    headers.add(Names.COOKIE, cookieVal);

    WebSocketClientHandshaker handshaker = WebSocketClientHandshakerFactory.newHandshaker(LOCATION,
            WebSocketVersion.V13, (String) null, false, headers);
    handler = new ClientHandler(handshaker);
    Bootstrap boot = new Bootstrap();
    boot.group(group).channel(NioSocketChannel.class).handler(new ChannelInitializer<SocketChannel>() {

        @Override
        protected void initChannel(SocketChannel ch) throws Exception {
            ch.pipeline().addLast("ssl", ssl.newHandler(ch.alloc(), "127.0.0.1", WS_PORT));
            ch.pipeline().addLast(new HttpClientCodec());
            ch.pipeline().addLast(new HttpObjectAggregator(8192));
            ch.pipeline().addLast(handler);
        }
    });
    ch = boot.connect("127.0.0.1", WS_PORT).sync().channel();
    // Wait until handshake is complete
    while (!handshaker.isHandshakeComplete()) {
        sleepUninterruptibly(500, TimeUnit.MILLISECONDS);
        LOG.debug("Waiting for Handshake to complete");
    }
}
项目:lannister    文件:HttpRequest.java   
protected void normalize() {
    normalizeParameters();

    String encoded = ClientCookieEncoder.STRICT.encode(cookies);
    if (encoded == null) { return; }

    headers().set(HttpHeaderNames.COOKIE, encoded);
}
项目:reactor-netty    文件:HttpClientOperations.java   
@Override
public HttpClientRequest addCookie(Cookie cookie) {
    if (!hasSentHeaders()) {
        this.requestHeaders.add(HttpHeaderNames.COOKIE,
                ClientCookieEncoder.STRICT.encode(cookie));
    }
    else {
        throw new IllegalStateException("Status and headers already sent");
    }
    return this;
}
项目:laputa    文件:HttpClient.java   
private void setCookies(HttpRequest request) {
  if (null == cookies || cookies.isEmpty()) {
    return;
  }
  List<Cookie> cookieList = new ArrayList<>(cookies.size());
  for (Map.Entry<String, String> entry : cookies.entrySet()) {
    cookieList.add(new DefaultCookie(entry.getKey(), entry.getValue()));
  }
  request.headers().set(COOKIE, ClientCookieEncoder.STRICT.encode(cookieList));
}
项目:divconq    文件:ClientHandler.java   
public void send(Message msg) {
    Logger.debug("Sending message: " + msg);

    try {
        if (this.chan != null) {
            if (this.info.getKind() == ConnectorKind.WebSocket)
                this.chan.writeAndFlush(new TextWebSocketFrame(msg.toString()));
            else {
                DefaultFullHttpRequest req = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST, this.info.getPath());

                req.headers().set(Names.HOST, this.info.getHost());
                req.headers().set(Names.USER_AGENT, "DivConq HyperAPI Client 1.0");
                req.headers().set(Names.CONNECTION, HttpHeaders.Values.KEEP_ALIVE);
                req.headers().set(Names.CONTENT_ENCODING, "UTF-8");
                req.headers().set(Names.CONTENT_TYPE, "application/json; charset=utf-8");
                req.headers().set(Names.COOKIE, ClientCookieEncoder.STRICT.encode(this.cookies.values()));

                // TODO make more efficient - UTF8 encode directly to buffer
                ByteBuf buf = Unpooled.copiedBuffer(msg.toString(), CharsetUtil.UTF_8);
                int clen = buf.readableBytes();
                req.content().writeBytes(buf);
                buf.release();

                // Add 'Content-Length' header only for a keep-alive connection.
                req.headers().set(Names.CONTENT_LENGTH, clen);

                this.chan.writeAndFlush(req);
            }
        }
    }
    catch (Exception x) {
        Logger.error("Send HTTP Message error: " + x);
    }
}
项目:mockserver    文件:HttpRequestToCurlSerializer.java   
private String getCookieHeader(HttpRequest request) {
    List<Cookie> cookies = new ArrayList<Cookie>();
    for (org.mockserver.model.Cookie cookie : request.getCookieList()) {
        cookies.add(new DefaultCookie(cookie.getName().getValue(), cookie.getValue().getValue()));
    }
    if (cookies.size() > 0) {
        return " -H '" + COOKIE + ": " + ClientCookieEncoder.LAX.encode(cookies) + "'";
    } else {
        return "";
    }
}
项目:qonduit    文件:HttpRequestDecoderTest.java   
private void addCookie(FullHttpRequest request) {
    request.headers().set(Names.COOKIE, ClientCookieEncoder.STRICT.encode(Constants.COOKIE_NAME, cookie));
}
项目:timely    文件:HttpRequestDecoderTest.java   
private void addCookie(FullHttpRequest request) {
    request.headers().set(Names.COOKIE, ClientCookieEncoder.STRICT.encode(Constants.COOKIE_NAME, cookie));
}
项目:riposte    文件:RequestInfoImplTest.java   
@Test
public void netty_helper_constructor_populates_request_info_appropriately() {
    // given
    String uri = "/some/uri/path/%24foobar%26?foo=bar&secondparam=secondvalue";
    Map<String, List<String>> expectedQueryParamMap = new HashMap<>();
    expectedQueryParamMap.put("foo", Arrays.asList("bar"));
    expectedQueryParamMap.put("secondparam", Arrays.asList("secondvalue"));
    HttpMethod method = HttpMethod.PATCH;
    String cookieName = UUID.randomUUID().toString();
    String cookieValue = UUID.randomUUID().toString();
    String content = UUID.randomUUID().toString();
    byte[] contentBytes = content.getBytes();
    Charset contentCharset = CharsetUtil.UTF_8;
    ByteBuf contentByteBuf = Unpooled.copiedBuffer(contentBytes);
    HttpHeaders headers = new DefaultHttpHeaders()
            .add("header1", "val1")
            .add(HttpHeaders.Names.CONTENT_TYPE, contentCharset)
            .add(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.KEEP_ALIVE)
            .add(HttpHeaders.Names.COOKIE, ClientCookieEncoder.LAX.encode(cookieName, cookieValue));
    HttpHeaders trailingHeaders = new DefaultHttpHeaders().add("trailingHeader1", "trailingVal1");
    HttpVersion protocolVersion = HttpVersion.HTTP_1_1;

    FullHttpRequest nettyRequestMock = mock(FullHttpRequest.class);
    doReturn(uri).when(nettyRequestMock).getUri();
    doReturn(method).when(nettyRequestMock).getMethod();
    doReturn(headers).when(nettyRequestMock).headers();
    doReturn(trailingHeaders).when(nettyRequestMock).trailingHeaders();
    doReturn(contentByteBuf).when(nettyRequestMock).content();
    doReturn(protocolVersion).when(nettyRequestMock).getProtocolVersion();

    // when
    RequestInfoImpl<?> requestInfo = new RequestInfoImpl<>(nettyRequestMock);

    // then
    assertThat("getUri was not the same value sent in", requestInfo.getUri(), is(uri));
    assertThat("getPath did not decode as expected", requestInfo.getPath(), is("/some/uri/path/$foobar&"));
    assertThat(requestInfo.getMethod(), is(method));
    assertThat(requestInfo.getHeaders(), is(headers));
    assertThat(requestInfo.getTrailingHeaders(), is(trailingHeaders));
    assertThat(requestInfo.getQueryParams(), notNullValue());
    assertThat(requestInfo.getQueryParams().parameters(), is(expectedQueryParamMap));
    assertThat(requestInfo.getCookies(), is(Sets.newHashSet(new DefaultCookie(cookieName, cookieValue))));
    assertThat(requestInfo.pathTemplate, nullValue());
    assertThat(requestInfo.pathParams.isEmpty(), is(true));
    assertThat(requestInfo.getRawContentBytes(), is(contentBytes));
    assertThat(requestInfo.getRawContent(), is(content));
    assertThat(requestInfo.content, nullValue());
    assertThat(requestInfo.getContentCharset(), is(contentCharset));
    assertThat(requestInfo.getProtocolVersion(), is(protocolVersion));
    assertThat(requestInfo.isKeepAliveRequested(), is(true));
}
项目:JavaAyo    文件:HttpUploadClient.java   
/**
 * Standard usage of HTTP API in Netty without file Upload (get is not able to achieve File upload
 * due to limitation on request size).
 *
 * @return the list of headers that will be used in every example after
 **/
private static List<Entry<String, String>> formget(
        Bootstrap bootstrap, String host, int port, String get, URI uriSimple) throws Exception {
    // XXX /formget
    // No use of HttpPostRequestEncoder since not a POST
    Channel channel = bootstrap.connect(host, port).sync().channel();

    // Prepare the HTTP request.
    QueryStringEncoder encoder = new QueryStringEncoder(get);
    // add Form attribute
    encoder.addParam("getform", "GET");
    encoder.addParam("info", "first value");
    encoder.addParam("secondinfo", "secondvalue ���&");
    // not the big one since it is not compatible with GET size
    // encoder.addParam("thirdinfo", textArea);
    encoder.addParam("thirdinfo", "third value\r\ntest second line\r\n\r\nnew line\r\n");
    encoder.addParam("Send", "Send");

    URI uriGet = new URI(encoder.toString());
    HttpRequest request = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, uriGet.toASCIIString());
    HttpHeaders headers = request.headers();
    headers.set(HttpHeaderNames.HOST, host);
    headers.set(HttpHeaderNames.CONNECTION, HttpHeaderValues.CLOSE);
    headers.set(HttpHeaderNames.ACCEPT_ENCODING, HttpHeaderValues.GZIP + "," + HttpHeaderValues.DEFLATE);

    headers.set(HttpHeaderNames.ACCEPT_CHARSET, "ISO-8859-1,utf-8;q=0.7,*;q=0.7");
    headers.set(HttpHeaderNames.ACCEPT_LANGUAGE, "fr");
    headers.set(HttpHeaderNames.REFERER, uriSimple.toString());
    headers.set(HttpHeaderNames.USER_AGENT, "Netty Simple Http Client side");
    headers.set(HttpHeaderNames.ACCEPT, "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");

    //connection will not close but needed
    // headers.set("Connection","keep-alive");
    // headers.set("Keep-Alive","300");

    headers.set(
            HttpHeaderNames.COOKIE, ClientCookieEncoder.STRICT.encode(
                    new DefaultCookie("my-cookie", "foo"),
                    new DefaultCookie("another-cookie", "bar"))
    );

    // send request
    channel.writeAndFlush(request);

    // Wait for the server to close the connection.
    channel.closeFuture().sync();

    // convert headers to list
    return headers.entries();
}
项目:JavaAyo    文件:HttpSnoopClient.java   
public static void main(String[] args) throws Exception {
    URI uri = new URI(URL);
    String scheme = uri.getScheme() == null? "http" : uri.getScheme();
    String host = uri.getHost() == null? "127.0.0.1" : uri.getHost();
    int port = uri.getPort();
    if (port == -1) {
        if ("http".equalsIgnoreCase(scheme)) {
            port = 80;
        } else if ("https".equalsIgnoreCase(scheme)) {
            port = 443;
        }
    }

    if (!"http".equalsIgnoreCase(scheme) && !"https".equalsIgnoreCase(scheme)) {
        System.err.println("Only HTTP(S) is supported.");
        return;
    }

    // Configure SSL context if necessary.
    final boolean ssl = "https".equalsIgnoreCase(scheme);
    final SslContext sslCtx;
    if (ssl) {
        sslCtx = SslContextBuilder.forClient()
            .trustManager(InsecureTrustManagerFactory.INSTANCE).build();
    } else {
        sslCtx = null;
    }

    // Configure the client.
    EventLoopGroup group = new NioEventLoopGroup();
    try {
        Bootstrap b = new Bootstrap();
        b.group(group)
         .channel(NioSocketChannel.class)
         .handler(new HttpSnoopClientInitializer(sslCtx));

        // Make the connection attempt.
        Channel ch = b.connect(host, port).sync().channel();

        // Prepare the HTTP request.
        HttpRequest request = new DefaultFullHttpRequest(
                HttpVersion.HTTP_1_1, HttpMethod.GET, uri.getRawPath());
        request.headers().set(HttpHeaderNames.HOST, host);
        request.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderValues.CLOSE);
        request.headers().set(HttpHeaderNames.ACCEPT_ENCODING, HttpHeaderValues.GZIP);

        // Set some example cookies.
        request.headers().set(
                HttpHeaderNames.COOKIE,
                ClientCookieEncoder.STRICT.encode(
                        new DefaultCookie("my-cookie", "foo"),
                        new DefaultCookie("another-cookie", "bar")));

        // Send the HTTP request.
        ch.writeAndFlush(request);

        // Wait for the server to close the connection.
        ch.closeFuture().sync();
    } finally {
        // Shut down executor threads to exit.
        group.shutdownGracefully();
    }
}
项目:nomulus    文件:HttpsRelayServiceHandler.java   
/**
 * Load session cookies in the cookie store and write them in to the HTTP request.
 *
 * <p>Multiple cookies are folded into one {@code Cookie} header per RFC 6265.
 *
 * @see <a href="https://tools.ietf.org/html/rfc6265#section-5.4">RFC 6265 5.4.The Cookie
 *     Header</a>
 */
private void loadCookies(FullHttpRequest request) {
  if (!cookieStore.isEmpty()) {
    request
        .headers()
        .set(HttpHeaderNames.COOKIE, ClientCookieEncoder.STRICT.encode(cookieStore.values()));
  }
}