Example usage for io.netty.handler.codec.http HttpMethod CONNECT

List of usage examples for io.netty.handler.codec.http HttpMethod CONNECT

Introduction

In this page you can find the example usage for io.netty.handler.codec.http HttpMethod CONNECT.

Prototype

HttpMethod CONNECT

To view the source code for io.netty.handler.codec.http HttpMethod CONNECT.

Click Source Link

Document

This specification reserves the method name CONNECT for use with a proxy that can dynamically switch to being a tunnel

Usage

From source file:org.asynchttpclient.providers.netty.request.NettyRequestFactory.java

License:Apache License

public NettyRequest newNettyRequest(Request request, URI uri, boolean forceConnect, ProxyServer proxyServer)
        throws IOException {

    HttpMethod method = forceConnect ? HttpMethod.CONNECT : HttpMethod.valueOf(request.getMethod());
    HttpVersion httpVersion = method == HttpMethod.CONNECT ? HttpVersion.HTTP_1_0 : HttpVersion.HTTP_1_1;
    String requestUri = requestUri(uri, proxyServer, method);

    NettyBody body = body(request, method);

    HttpRequest httpRequest;//from   ww  w  . j  av  a 2s  .com
    NettyRequest nettyRequest;
    if (body instanceof NettyByteArrayBody) {
        byte[] bytes = NettyByteArrayBody.class.cast(body).getBytes();
        httpRequest = new DefaultFullHttpRequest(httpVersion, method, requestUri,
                Unpooled.wrappedBuffer(bytes));
        // body is passed as null as it's written directly with the request
        nettyRequest = new NettyRequest(httpRequest, null);

    } else if (body == null) {
        httpRequest = new DefaultFullHttpRequest(httpVersion, method, requestUri);
        nettyRequest = new NettyRequest(httpRequest, null);

    } else {
        httpRequest = new DefaultHttpRequest(httpVersion, method, requestUri);
        nettyRequest = new NettyRequest(httpRequest, body);
    }

    if (method != HttpMethod.CONNECT) {
        // assign headers as configured on request
        for (Entry<String, List<String>> header : request.getHeaders()) {
            httpRequest.headers().set(header.getKey(), header.getValue());
        }

        if (isNonEmpty(request.getCookies()))
            httpRequest.headers().set(HttpHeaders.Names.COOKIE, CookieEncoder.encode(request.getCookies()));

        if (config.isCompressionEnabled())
            httpRequest.headers().set(HttpHeaders.Names.ACCEPT_ENCODING, GZIP_DEFLATE);
    }

    if (body != null) {
        if (body.getContentLength() >= 0)
            httpRequest.headers().set(HttpHeaders.Names.CONTENT_LENGTH, body.getContentLength());
        else
            httpRequest.headers().set(HttpHeaders.Names.TRANSFER_ENCODING, HttpHeaders.Values.CHUNKED);

        if (body.getContentType() != null)
            httpRequest.headers().set(HttpHeaders.Names.CONTENT_TYPE, body.getContentType());
    }

    // connection header and friends
    boolean webSocket = isWebSocket(uri.getScheme());
    if (method != HttpMethod.CONNECT && webSocket) {
        httpRequest.headers().set(HttpHeaders.Names.UPGRADE, HttpHeaders.Values.WEBSOCKET);
        httpRequest.headers().set(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.UPGRADE);
        httpRequest.headers().set(HttpHeaders.Names.ORIGIN, "http://" + uri.getHost() + ":"
                + (uri.getPort() == -1 ? isSecure(uri.getScheme()) ? 443 : 80 : uri.getPort()));
        httpRequest.headers().set(HttpHeaders.Names.SEC_WEBSOCKET_KEY, WebSocketUtil.getKey());
        httpRequest.headers().set(HttpHeaders.Names.SEC_WEBSOCKET_VERSION, "13");

    } else if (!httpRequest.headers().contains(HttpHeaders.Names.CONNECTION)) {
        httpRequest.headers().set(HttpHeaders.Names.CONNECTION,
                AsyncHttpProviderUtils.keepAliveHeaderValue(config));
    }

    Realm realm = request.getRealm() != null ? request.getRealm() : config.getRealm();

    String hostHeader = hostHeader(request, uri, realm);
    if (hostHeader != null)
        httpRequest.headers().set(HttpHeaders.Names.HOST, hostHeader);

    String authorizationHeader = authorizationHeader(request, uri, proxyServer, realm);
    if (authorizationHeader != null)
        // don't override authorization but append
        httpRequest.headers().add(HttpHeaders.Names.AUTHORIZATION, authorizationHeader);

    String proxyAuthorizationHeader = proxyAuthorizationHeader(request, proxyServer, method);
    if (proxyAuthorizationHeader != null)
        httpRequest.headers().set(HttpHeaders.Names.PROXY_AUTHORIZATION, proxyAuthorizationHeader);

    // Add default accept headers
    if (!httpRequest.headers().contains(HttpHeaders.Names.ACCEPT))
        httpRequest.headers().set(HttpHeaders.Names.ACCEPT, "*/*");

    // Add default user agent
    if (!httpRequest.headers().contains(HttpHeaders.Names.USER_AGENT)) {
        String userAgent = config.getUserAgent() != null ? config.getUserAgent()
                : AsyncHttpProviderUtils.constructUserAgent(NettyAsyncHttpProvider.class, config);
        httpRequest.headers().set(HttpHeaders.Names.USER_AGENT, userAgent);
    }

    return nettyRequest;
}

From source file:org.asynchttpclient.providers.netty.request.NettyRequests.java

License:Apache License

public static HttpRequest newNettyRequest(AsyncHttpClientConfig config, Request request, URI uri,
        boolean allowConnect, ProxyServer proxyServer) throws IOException {

    HttpMethod method = null;//  w ww  .java 2  s  .  c  o  m
    if (allowConnect && proxyServer != null && isSecure(uri))
        method = HttpMethod.CONNECT;
    else
        method = HttpMethod.valueOf(request.getMethod());

    String host = null;
    HttpVersion httpVersion;
    String requestUri;
    Map<String, Object> headers = new HashMap<String, Object>();
    String authorizationHeader = null;
    ByteBuf content = null;
    boolean webSocket = isWebSocket(uri);

    if (request.getVirtualHost() != null) {
        host = request.getVirtualHost();
    } else {
        host = AsyncHttpProviderUtils.getHost(uri);
    }

    if (method == HttpMethod.CONNECT) {
        httpVersion = HttpVersion.HTTP_1_0;
        requestUri = AsyncHttpProviderUtils.getAuthority(uri);
    } else {
        httpVersion = HttpVersion.HTTP_1_1;
        if (proxyServer != null && !(isSecure(uri) && config.isUseRelativeURIsWithSSLProxies()))
            requestUri = uri.toString();
        else if (uri.getRawQuery() != null)
            requestUri = uri.getRawPath() + "?" + uri.getRawQuery();
        else
            requestUri = uri.getRawPath();
    }

    if (webSocket) {
        headers.put(HttpHeaders.Names.UPGRADE, HttpHeaders.Values.WEBSOCKET);
        headers.put(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.UPGRADE);
        headers.put(HttpHeaders.Names.ORIGIN, "http://" + uri.getHost() + ":"
                + (uri.getPort() == -1 ? isSecure(uri.getScheme()) ? 443 : 80 : uri.getPort()));
        headers.put(HttpHeaders.Names.SEC_WEBSOCKET_KEY, WebSocketUtil.getKey());
        headers.put(HttpHeaders.Names.SEC_WEBSOCKET_VERSION, "13");
    }

    if (host != null) {
        if (request.getVirtualHost() != null || uri.getPort() == -1) {
            headers.put(HttpHeaders.Names.HOST, host);
        } else {
            headers.put(HttpHeaders.Names.HOST, host + ":" + uri.getPort());
        }
    } else {
        host = "127.0.0.1";
    }

    if (method != HttpMethod.CONNECT) {
        if (config.isCompressionEnabled()) {
            headers.put(HttpHeaders.Names.ACCEPT_ENCODING, GZIP_DEFLATE);
        }
    } else {
        List<String> auth = request.getHeaders().get(HttpHeaders.Names.PROXY_AUTHORIZATION);
        if (isNTLM(auth)) {
            headers.put(HttpHeaders.Names.PROXY_AUTHORIZATION, auth.get(0));
        }
    }
    Realm realm = request.getRealm() != null ? request.getRealm() : config.getRealm();

    if (realm != null && realm.getUsePreemptiveAuth()) {

        String domain = realm.getNtlmDomain();
        if (proxyServer != null && proxyServer.getNtlmDomain() != null) {
            domain = proxyServer.getNtlmDomain();
        }

        String authHost = realm.getNtlmHost();
        if (proxyServer != null && proxyServer.getHost() != null) {
            host = proxyServer.getHost();
        }

        switch (realm.getAuthScheme()) {
        case BASIC:
            authorizationHeader = AuthenticatorUtils.computeBasicAuthentication(realm);
            break;
        case DIGEST:
            if (isNonEmpty(realm.getNonce())) {
                try {
                    authorizationHeader = AuthenticatorUtils.computeDigestAuthentication(realm);
                } catch (NoSuchAlgorithmException e) {
                    throw new SecurityException(e);
                }
            }
            break;
        case NTLM:
            try {
                String msg = NTLMEngine.INSTANCE.generateType1Msg("NTLM " + domain, authHost);
                authorizationHeader = "NTLM " + msg;
            } catch (NTLMEngineException e) {
                throw new IOException(e);
            }
            break;
        case KERBEROS:
        case SPNEGO:
            String challengeHeader = null;
            String server = proxyServer == null ? host : proxyServer.getHost();
            try {
                challengeHeader = SpnegoEngine.instance().generateToken(server);
            } catch (Throwable e) {
                throw new IOException(e);
            }
            authorizationHeader = "Negotiate " + challengeHeader;
            break;
        case NONE:
            break;
        default:
            throw new IllegalStateException("Invalid Authentication " + realm);
        }
    }

    if (!webSocket && !request.getHeaders().containsKey(HttpHeaders.Names.CONNECTION)) {
        headers.put(HttpHeaders.Names.CONNECTION, AsyncHttpProviderUtils.keepAliveHeaderValue(config));
    }

    if (proxyServer != null) {
        // FIXME Wikipedia says that Proxy-Connection was a misunderstanding of Connection http://en.wikipedia.org/wiki/List_of_HTTP_header_fields
        if (!request.getHeaders().containsKey("Proxy-Connection")) {
            headers.put("Proxy-Connection", AsyncHttpProviderUtils.keepAliveHeaderValue(config));
        }

        if (proxyServer.getPrincipal() != null) {
            if (isNonEmpty(proxyServer.getNtlmDomain())) {

                List<String> auth = request.getHeaders().get(HttpHeaders.Names.PROXY_AUTHORIZATION);
                if (!isNTLM(auth)) {
                    try {
                        String msg = NTLMEngine.INSTANCE.generateType1Msg(proxyServer.getNtlmDomain(),
                                proxyServer.getHost());
                        headers.put(HttpHeaders.Names.PROXY_AUTHORIZATION, "NTLM " + msg);
                    } catch (NTLMEngineException e) {
                        IOException ie = new IOException();
                        ie.initCause(e);
                        throw ie;
                    }
                }
            } else {
                headers.put(HttpHeaders.Names.PROXY_AUTHORIZATION,
                        AuthenticatorUtils.computeBasicAuthentication(proxyServer));
            }
        }
    }

    // Add default accept headers
    if (!request.getHeaders().containsKey(HttpHeaders.Names.ACCEPT)) {
        headers.put(HttpHeaders.Names.ACCEPT, "*/*");
    }

    String userAgentHeader = request.getHeaders().getFirstValue(HttpHeaders.Names.USER_AGENT);
    if (userAgentHeader != null) {
        headers.put(HttpHeaders.Names.USER_AGENT, userAgentHeader);
    } else if (config.getUserAgent() != null) {
        headers.put(HttpHeaders.Names.USER_AGENT, config.getUserAgent());
    } else {
        headers.put(HttpHeaders.Names.USER_AGENT,
                AsyncHttpProviderUtils.constructUserAgent(NettyAsyncHttpProvider.class, config));
    }

    boolean hasDeferredContent = false;
    if (method != HttpMethod.CONNECT) {
        if (isNonEmpty(request.getCookies())) {
            headers.put(HttpHeaders.Names.COOKIE,
                    CookieEncoder.encodeClientSide(request.getCookies(), config.isRfc6265CookieEncoding()));
        }

        String bodyCharset = request.getBodyEncoding() == null ? DEFAULT_CHARSET : request.getBodyEncoding();

        if (request.getByteData() != null) {
            headers.put(HttpHeaders.Names.CONTENT_LENGTH, request.getByteData().length);
            content = Unpooled.wrappedBuffer(request.getByteData());

        } else if (request.getStringData() != null) {
            byte[] bytes = request.getStringData().getBytes(bodyCharset);
            headers.put(HttpHeaders.Names.CONTENT_LENGTH, bytes.length);
            content = Unpooled.wrappedBuffer(bytes);

        } else if (request.getStreamData() != null) {
            hasDeferredContent = true;
            headers.put(HttpHeaders.Names.TRANSFER_ENCODING, HttpHeaders.Values.CHUNKED);

        } else if (isNonEmpty(request.getParams())) {
            StringBuilder sb = new StringBuilder();
            for (final Entry<String, List<String>> paramEntry : request.getParams()) {
                final String key = paramEntry.getKey();
                for (final String value : paramEntry.getValue()) {
                    UTF8UrlEncoder.appendEncoded(sb, key);
                    sb.append("=");
                    UTF8UrlEncoder.appendEncoded(sb, value);
                    sb.append("&");
                }
            }
            sb.setLength(sb.length() - 1);
            byte[] bytes = sb.toString().getBytes(bodyCharset);
            headers.put(HttpHeaders.Names.CONTENT_LENGTH, bytes.length);
            content = Unpooled.wrappedBuffer(bytes);

            if (!request.getHeaders().containsKey(HttpHeaders.Names.CONTENT_TYPE)) {
                headers.put(HttpHeaders.Names.CONTENT_TYPE,
                        HttpHeaders.Values.APPLICATION_X_WWW_FORM_URLENCODED);
            }

        } else if (request.getParts() != null) {
            // FIXME use Netty multipart
            MultipartRequestEntity mre = AsyncHttpProviderUtils.createMultipartRequestEntity(request.getParts(),
                    request.getHeaders());

            headers.put(HttpHeaders.Names.CONTENT_TYPE, mre.getContentType());
            if (mre.getContentLength() >= 0) {
                headers.put(HttpHeaders.Names.CONTENT_LENGTH, mre.getContentLength());
            }
            hasDeferredContent = true;

        } else if (request.getFile() != null) {
            File file = request.getFile();
            if (!file.isFile()) {
                throw new IOException(
                        String.format("File %s is not a file or doesn't exist", file.getAbsolutePath()));
            }
            headers.put(HttpHeaders.Names.CONTENT_LENGTH, file.length());
            hasDeferredContent = true;

        } else if (request.getBodyGenerator() != null) {
            hasDeferredContent = true;
        }
    }

    HttpRequest nettyRequest;
    if (hasDeferredContent) {
        nettyRequest = new DefaultHttpRequest(httpVersion, method, requestUri);
    } else if (content != null) {
        nettyRequest = new DefaultFullHttpRequest(httpVersion, method, requestUri, content);
    } else {
        nettyRequest = new DefaultFullHttpRequest(httpVersion, method, requestUri);
    }

    // assign headers as configured on request
    if (method != HttpMethod.CONNECT) {
        for (Entry<String, List<String>> header : request.getHeaders()) {
            nettyRequest.headers().set(header.getKey(), header.getValue());
        }
    }

    // override with computed ones
    for (Entry<String, Object> header : headers.entrySet()) {
        nettyRequest.headers().set(header.getKey(), header.getValue());
    }

    if (authorizationHeader != null) {
        // don't override authorization but append
        nettyRequest.headers().add(HttpHeaders.Names.AUTHORIZATION, authorizationHeader);
    }

    return nettyRequest;
}

From source file:org.asynchttpclient.providers.netty.request.NettyRequestSender.java

License:Apache License

public <T> ListenableFuture<T> sendRequest(final Request request, //
        final AsyncHandler<T> asyncHandler, //
        NettyResponseFuture<T> future, //
        boolean reclaimCache) throws IOException {

    if (closed.get()) {
        throw new IOException("Closed");
    }/*from  w  w  w.  jav a  2s.  c om*/

    // FIXME really useful? Why not do this check when building the request?
    if (request.getURI().getScheme().startsWith(WEBSOCKET)
            && !validateWebSocketRequest(request, asyncHandler)) {
        throw new IOException("WebSocket method must be a GET");
    }

    URI uri = config.isUseRawUrl() ? request.getRawURI() : request.getURI();
    ProxyServer proxyServer = ProxyUtils.getProxyServer(config, request);
    boolean resultOfAConnect = future != null && future.getNettyRequest() != null
            && future.getNettyRequest().getHttpRequest().getMethod() == HttpMethod.CONNECT;
    boolean useProxy = proxyServer != null && !resultOfAConnect;

    if (useProxy && isSecure(uri)) {
        // SSL proxy, have to handle CONNECT
        if (future != null && future.isConnectAllowed())
            // CONNECT forced
            return sendRequestWithCertainForceConnect(request, asyncHandler, future, reclaimCache, uri,
                    proxyServer, true, true);
        else
            return sendRequestThroughSslProxy(request, asyncHandler, future, reclaimCache, uri, proxyServer);
    } else
        return sendRequestWithCertainForceConnect(request, asyncHandler, future, reclaimCache, uri, proxyServer,
                useProxy, false);
}

From source file:org.asynchttpclient.providers.netty.request.NettyRequestSender.java

License:Apache License

public final <T> void writeRequest(NettyResponseFuture<T> future, Channel channel) {
    try {//from   w  w w.j a  v  a  2 s. co  m
        // if the channel is dead because it was pooled and the remote server decided to close it,
        // we just let it go and the channelInactive do its work
        if (!channel.isOpen() || !channel.isActive()) {
            return;
        }

        NettyRequest nettyRequest = future.getNettyRequest();
        HttpRequest httpRequest = nettyRequest.getHttpRequest();
        AsyncHandler<T> handler = future.getAsyncHandler();

        if (handler instanceof TransferCompletionHandler) {
            configureTransferAdapter(handler, httpRequest);
        }

        if (!future.isHeadersAlreadyWrittenOnContinue()) {
            try {
                if (future.getAsyncHandler() instanceof AsyncHandlerExtensions) {
                    AsyncHandlerExtensions.class.cast(future.getAsyncHandler()).onRequestSent();
                }
                channel.writeAndFlush(httpRequest, channel.newProgressivePromise())
                        .addListener(new ProgressListener(config, future.getAsyncHandler(), future, true, 0L));
            } catch (Throwable cause) {
                // FIXME why not notify?
                LOGGER.debug(cause.getMessage(), cause);
                try {
                    channel.close();
                } catch (RuntimeException ex) {
                    LOGGER.debug(ex.getMessage(), ex);
                }
                return;
            }
        }

        if (!future.isDontWriteBodyBecauseExpectContinue()
                && !httpRequest.getMethod().equals(HttpMethod.CONNECT) && nettyRequest.getBody() != null)
            nettyRequest.getBody().write(channel, future, config);

    } catch (Throwable ioe) {
        try {
            channel.close();
        } catch (RuntimeException ex) {
            LOGGER.debug(ex.getMessage(), ex);
        }
    }

    scheduleTimeouts(future);
}

From source file:org.asynchttpclient.providers.netty4.handler.HttpProtocol.java

License:Open Source License

private boolean exitAfterHandling407(//
        Channel channel, //
        NettyResponseFuture<?> future, //
        HttpResponse response, //
        Request request, //
        int statusCode, //
        Realm realm, //
        ProxyServer proxyServer) throws Exception {

    if (statusCode == PROXY_AUTHENTICATION_REQUIRED.code() && realm != null && !future.getAndSetAuth(true)) {

        List<String> proxyAuthHeaders = response.headers().getAll(HttpHeaders.Names.PROXY_AUTHENTICATE);

        if (!proxyAuthHeaders.isEmpty()) {
            logger.debug("Sending proxy authentication to {}", request.getUri());

            future.setState(NettyResponseFuture.STATE.NEW);
            Realm newRealm = null;/* ww  w. ja v a 2 s.  c om*/
            FluentCaseInsensitiveStringsMap requestHeaders = request.getHeaders();

            boolean negociate = proxyAuthHeaders.contains("Negotiate");
            String ntlmAuthenticate = getNTLM(proxyAuthHeaders);
            if (!proxyAuthHeaders.contains("Kerberos") && ntlmAuthenticate != null) {
                newRealm = ntlmProxyChallenge(ntlmAuthenticate, request, proxyServer, requestHeaders, realm,
                        future, true);
                // SPNEGO KERBEROS
            } else if (negociate) {
                newRealm = kerberosChallenge(channel, proxyAuthHeaders, request, proxyServer, requestHeaders,
                        realm, future, true);
                if (newRealm == null)
                    return true;
            } else {
                newRealm = new Realm.RealmBuilder().clone(realm)//
                        .setScheme(realm.getAuthScheme())//
                        .setUri(request.getUri())//
                        .setOmitQuery(true)//
                        .setMethodName(HttpMethod.CONNECT.name())//
                        .setUsePreemptiveAuth(true)//
                        .parseProxyAuthenticateHeader(proxyAuthHeaders.get(0))//
                        .build();
            }

            future.setReuseChannel(true);
            future.setConnectAllowed(true);
            Request nextRequest = new RequestBuilder(future.getRequest()).setHeaders(requestHeaders)
                    .setRealm(newRealm).build();
            requestSender.sendNextRequest(nextRequest, future);
            return true;
        }
    }
    return false;
}

From source file:org.asynchttpclient.providers.netty4.handler.HttpProtocol.java

License:Open Source License

private boolean exitAfterHandlingConnect(//
        final Channel channel, //
        final NettyResponseFuture<?> future, //
        final Request request, //
        ProxyServer proxyServer, //
        int statusCode, //
        HttpRequest httpRequest) throws IOException {

    if (statusCode == OK.code() && httpRequest.getMethod() == HttpMethod.CONNECT) {

        if (future.isKeepAlive())
            future.attachChannel(channel, true);

        try {//from  w  w w .j  a  v a2  s. c o  m
            Uri requestUri = request.getUri();
            String scheme = requestUri.getScheme();
            String host = requestUri.getHost();
            int port = getDefaultPort(requestUri);

            logger.debug("Connecting to proxy {} for scheme {}", proxyServer, scheme);
            channelManager.upgradeProtocol(channel.pipeline(), scheme, host, port);

        } catch (Throwable ex) {
            requestSender.abort(channel, future, ex);
        }

        future.setReuseChannel(true);
        future.setConnectAllowed(false);
        requestSender.sendNextRequest(new RequestBuilder(future.getRequest()).build(), future);
        return true;
    }

    return false;
}

From source file:org.asynchttpclient.providers.netty4.request.NettyRequestFactory.java

License:Open Source License

private String requestUri(Uri uri, ProxyServer proxyServer, HttpMethod method) {
    if (method == HttpMethod.CONNECT)
        return getAuthority(uri);

    else if (proxyServer != null && !(useProxyConnect(uri) && config.isUseRelativeURIsWithConnectProxies()))
        return uri.toUrl();

    else {/* www.j av  a  2s .co  m*/
        String path = getNonEmptyPath(uri);
        if (isNonEmpty(uri.getQuery()))
            return path + "?" + uri.getQuery();
        else
            return path;
    }
}

From source file:org.asynchttpclient.providers.netty4.request.NettyRequestFactory.java

License:Open Source License

public String firstRequestOnlyProxyAuthorizationHeader(Request request, ProxyServer proxyServer,
        HttpMethod method) throws IOException {
    String proxyAuthorization = null;

    if (method == HttpMethod.CONNECT) {
        List<String> auth = request.getHeaders().get(HttpHeaders.Names.PROXY_AUTHORIZATION);
        String ntlmHeader = getNTLM(auth);
        if (ntlmHeader != null) {
            proxyAuthorization = ntlmHeader;
        }/*w w w .  ja  v  a 2  s  . c om*/

    } else if (proxyServer != null && proxyServer.getPrincipal() != null
            && isNonEmpty(proxyServer.getNtlmDomain())) {
        List<String> auth = request.getHeaders().get(HttpHeaders.Names.PROXY_AUTHORIZATION);
        if (getNTLM(auth) == null) {
            String msg = NTLMEngine.INSTANCE.generateType1Msg();
            proxyAuthorization = "NTLM " + msg;
        }
    }

    return proxyAuthorization;
}

From source file:org.asynchttpclient.providers.netty4.request.NettyRequestFactory.java

License:Open Source License

private String systematicProxyAuthorizationHeader(Request request, ProxyServer proxyServer, HttpMethod method) {

    String proxyAuthorization = null;

    if (method != HttpMethod.CONNECT && proxyServer != null && proxyServer.getPrincipal() != null
            && !isNonEmpty(proxyServer.getNtlmDomain())) {
        proxyAuthorization = computeBasicAuthentication(proxyServer);
    }//from ww w . ja  v  a2  s .c  o  m

    return proxyAuthorization;
}

From source file:org.asynchttpclient.providers.netty4.request.NettyRequestFactory.java

License:Open Source License

private NettyBody body(Request request, HttpMethod method) throws IOException {
    NettyBody nettyBody = null;/* ww  w  .  j  a  va  2 s  . c  o m*/
    if (method != HttpMethod.CONNECT) {

        Charset bodyCharset = request.getBodyEncoding() == null ? DEFAULT_CHARSET
                : Charset.forName(request.getBodyEncoding());

        if (request.getByteData() != null)
            nettyBody = new NettyByteArrayBody(request.getByteData());

        else if (request.getCompositeByteData() != null)
            nettyBody = new NettyCompositeByteArrayBody(request.getCompositeByteData());

        else if (request.getStringData() != null)
            nettyBody = new NettyByteArrayBody(request.getStringData().getBytes(bodyCharset));

        else if (request.getStreamData() != null)
            nettyBody = new NettyInputStreamBody(request.getStreamData());

        else if (isNonEmpty(request.getFormParams())) {

            String contentType = null;
            if (!request.getHeaders().containsKey(HttpHeaders.Names.CONTENT_TYPE))
                contentType = HttpHeaders.Values.APPLICATION_X_WWW_FORM_URLENCODED;

            nettyBody = new NettyByteArrayBody(computeBodyFromParams(request.getFormParams(), bodyCharset),
                    contentType);

        } else if (isNonEmpty(request.getParts()))
            nettyBody = new NettyMultipartBody(request.getParts(), request.getHeaders(), nettyConfig);

        else if (request.getFile() != null)
            nettyBody = new NettyFileBody(request.getFile(), nettyConfig);

        else if (request.getBodyGenerator() instanceof FileBodyGenerator) {
            FileBodyGenerator fileBodyGenerator = (FileBodyGenerator) request.getBodyGenerator();
            nettyBody = new NettyFileBody(fileBodyGenerator.getFile(), fileBodyGenerator.getRegionSeek(),
                    fileBodyGenerator.getRegionLength(), nettyConfig);

        } else if (request.getBodyGenerator() instanceof InputStreamBodyGenerator)
            nettyBody = new NettyInputStreamBody(
                    InputStreamBodyGenerator.class.cast(request.getBodyGenerator()).getInputStream());

        else if (request.getBodyGenerator() != null)
            nettyBody = new NettyBodyBody(request.getBodyGenerator().createBody(), nettyConfig);
    }

    return nettyBody;
}