List of usage examples for io.netty.handler.codec.http HttpMethod CONNECT
HttpMethod CONNECT
To view the source code for io.netty.handler.codec.http HttpMethod CONNECT.
Click Source Link
From source file:org.asynchttpclient.netty.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); Uri requestUri = request.getUri(); String scheme = requestUri.getScheme(); String host = requestUri.getHost(); int port = getExplicitPort(requestUri); logger.debug("Connecting to proxy {} for scheme {}", proxyServer, scheme); try {//from w ww. j ava 2s . co m channelManager.upgradeProtocol(channel.pipeline(), scheme, host, port); future.setReuseChannel(true); future.setConnectAllowed(false); requestSender.drainChannelAndExecuteNextRequest(channel, future, new RequestBuilder(future.getRequest()).build()); } catch (GeneralSecurityException ex) { requestSender.abort(channel, future, ex); } return true; } return false; }
From source file:org.asynchttpclient.netty.handler.intercept.Interceptors.java
License:Open Source License
public boolean exitAfterIntercept(// Channel channel, // NettyResponseFuture<?> future, // AsyncHandler<?> handler, // HttpResponse response, // HttpResponseStatus status, // HttpResponseHeaders responseHeaders) throws Exception { HttpRequest httpRequest = future.getNettyRequest().getHttpRequest(); ProxyServer proxyServer = future.getProxyServer(); int statusCode = response.getStatus().code(); Request request = future.getCurrentRequest(); Realm realm = request.getRealm() != null ? request.getRealm() : config.getRealm(); if (hasResponseFilters && responseFiltersInterceptor.exitAfterProcessingFilters(channel, future, handler, status, responseHeaders)) {/*from w ww . j av a2 s.c o m*/ return true; } if (statusCode == UNAUTHORIZED_401) { return unauthorized401Interceptor.exitAfterHandling401(channel, future, response, request, statusCode, realm, proxyServer, httpRequest); } else if (statusCode == PROXY_AUTHENTICATION_REQUIRED_407) { return proxyUnauthorized407Interceptor.exitAfterHandling407(channel, future, response, request, statusCode, proxyServer, httpRequest); } else if (statusCode == CONTINUE_100) { return continue100Interceptor.exitAfterHandling100(channel, future, statusCode); } else if (Redirect30xInterceptor.REDIRECT_STATUSES.contains(statusCode)) { return redirect30xInterceptor.exitAfterHandlingRedirect(channel, future, response, request, statusCode, realm); } else if (httpRequest.getMethod() == HttpMethod.CONNECT && statusCode == OK_200) { return connectSuccessInterceptor.exitAfterHandlingConnect(channel, future, request, proxyServer, statusCode, httpRequest); } return false; }
From source file:org.asynchttpclient.netty.request.NettyRequestFactory.java
License:Open Source License
public NettyRequest newNettyRequest(Request request, boolean forceConnect, ProxyServer proxyServer, Realm realm, Realm proxyRealm) {/*ww w.ja va 2 s . c o m*/ Uri uri = request.getUri(); HttpMethod method = forceConnect ? HttpMethod.CONNECT : HttpMethod.valueOf(request.getMethod()); boolean connect = method == HttpMethod.CONNECT; HttpVersion httpVersion = HttpVersion.HTTP_1_1; String requestUri = requestUri(uri, proxyServer, connect); NettyBody body = body(request, connect); HttpRequest httpRequest; NettyRequest nettyRequest; if (body instanceof NettyDirectBody) { ByteBuf buf = NettyDirectBody.class.cast(body).byteBuf(); httpRequest = new DefaultFullHttpRequest(httpVersion, method, requestUri, buf); // 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); } HttpHeaders headers = httpRequest.headers(); if (connect) { // assign proxy-auth as configured on request headers.set(PROXY_AUTHORIZATION, request.getHeaders().getAll(PROXY_AUTHORIZATION)); } else { // assign headers as configured on request headers.set(request.getHeaders()); if (isNonEmpty(request.getCookies())) headers.set(COOKIE, CookieEncoder.encode(request.getCookies())); String userDefinedAcceptEncoding = headers.get(ACCEPT_ENCODING); if (userDefinedAcceptEncoding != null) { // we don't support Brotly ATM if (userDefinedAcceptEncoding.endsWith(BROTLY_ACCEPT_ENCODING_SUFFIX)) { headers.set(ACCEPT_ENCODING, userDefinedAcceptEncoding.subSequence(0, userDefinedAcceptEncoding.length() - BROTLY_ACCEPT_ENCODING_SUFFIX.length())); } } else if (config.isCompressionEnforced()) { headers.set(ACCEPT_ENCODING, GZIP_DEFLATE); } } if (body != null) { if (body.getContentLength() < 0) headers.set(TRANSFER_ENCODING, HttpHeaders.Values.CHUNKED); else headers.set(CONTENT_LENGTH, body.getContentLength()); if (body.getContentType() != null) headers.set(CONTENT_TYPE, body.getContentType()); } // connection header and friends if (!connect && uri.isWebSocket()) { headers.set(HttpHeaders.Names.UPGRADE, HttpHeaders.Values.WEBSOCKET)// .set(CONNECTION, HttpHeaders.Values.UPGRADE)// .set(ORIGIN, "http://" + uri.getHost() + ":" + uri.getExplicitPort())// .set(SEC_WEBSOCKET_KEY, getKey())// .set(SEC_WEBSOCKET_VERSION, "13"); } else if (!headers.contains(CONNECTION)) { String connectionHeaderValue = connectionHeader(config.isKeepAlive(), httpVersion); if (connectionHeaderValue != null) headers.set(CONNECTION, connectionHeaderValue); } if (!headers.contains(HOST)) headers.set(HOST, hostHeader(request, uri)); // don't override authorization but append addAuthorizationHeader(headers, perRequestAuthorizationHeader(realm)); // only set proxy auth on request over plain HTTP, or when performing CONNECT if (!uri.isSecured() || connect) { setProxyAuthorizationHeader(headers, perRequestProxyAuthorizationHeader(proxyRealm)); } // Add default accept headers if (!headers.contains(ACCEPT)) headers.set(ACCEPT, "*/*"); // Add default user agent if (!headers.contains(USER_AGENT) && config.getUserAgent() != null) headers.set(USER_AGENT, config.getUserAgent()); return nettyRequest; }
From source file:org.asynchttpclient.netty.request.NettyRequestSender.java
License:Open Source License
private boolean isConnectDone(Request request, NettyResponseFuture<?> future) { return future != null // && future.getNettyRequest() != null // && future.getNettyRequest().getHttpRequest().getMethod() == HttpMethod.CONNECT // && !request.getMethod().equals(CONNECT); }
From source file:org.asynchttpclient.netty.request.NettyRequestSender.java
License:Open Source License
public <T> void writeRequest(NettyResponseFuture<T> future, Channel channel) { NettyRequest nettyRequest = future.getNettyRequest(); HttpRequest httpRequest = nettyRequest.getHttpRequest(); AsyncHandler<T> handler = future.getAsyncHandler(); // 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 (!Channels.isChannelValid(channel)) return;/* w w w . ja v a2 s . com*/ try { if (handler instanceof TransferCompletionHandler) configureTransferAdapter(handler, httpRequest); boolean writeBody = !future.isDontWriteBodyBecauseExpectContinue() && httpRequest.getMethod() != HttpMethod.CONNECT && nettyRequest.getBody() != null; if (!future.isHeadersAlreadyWrittenOnContinue()) { if (handler instanceof AsyncHandlerExtensions) { AsyncHandlerExtensions.class.cast(handler).onRequestSend(nettyRequest); } // if the request has a body, we want to track progress if (writeBody) { ChannelProgressivePromise promise = channel.newProgressivePromise(); ChannelFuture f = channel.write(httpRequest, promise); f.addListener(new WriteProgressListener(future, true, 0L)); } else { // we can just track write completion ChannelPromise promise = channel.newPromise(); ChannelFuture f = channel.writeAndFlush(httpRequest, promise); f.addListener(new WriteCompleteListener(future)); } } if (writeBody) nettyRequest.getBody().write(channel, future); // don't bother scheduling read timeout if channel became invalid if (Channels.isChannelValid(channel)) scheduleReadTimeout(future); } catch (Exception e) { LOGGER.error("Can't write request", e); abort(channel, future, e); } }
From source file:org.asynchttpclient.providers.netty.handler.HttpProtocol.java
License:Apache License
private boolean handleProxyAuthenticationRequiredAndExit(int statusCode, // Realm realm, // final Request request, // HttpResponse response, // final NettyResponseFuture<?> future, // ProxyServer proxyServer) throws Exception { if (statusCode == PROXY_AUTHENTICATION_REQUIRED.code() && realm != null) { List<String> proxyAuthenticateHeaders = response.headers().getAll(HttpHeaders.Names.PROXY_AUTHENTICATE); if (!proxyAuthenticateHeaders.isEmpty() && !future.getAndSetAuth(true)) { LOGGER.debug("Sending proxy authentication to {}", request.getURI()); future.setState(NettyResponseFuture.STATE.NEW); Realm newRealm = null;/* w w w . j ava 2 s . c o m*/ boolean negociate = proxyAuthenticateHeaders.contains("Negotiate"); if (!proxyAuthenticateHeaders.contains("Kerberos") && (isNTLM(proxyAuthenticateHeaders) || negociate)) { newRealm = ntlmProxyChallenge(proxyAuthenticateHeaders, request, proxyServer, request.getHeaders(), realm, future, true); // SPNEGO KERBEROS } else if (negociate) { newRealm = kerberosChallenge(proxyAuthenticateHeaders, request, proxyServer, request.getHeaders(), realm, future, true); if (newRealm == null) return true; } else { newRealm = new Realm.RealmBuilder().clone(realm)// .setScheme(realm.getAuthScheme())// .setUri("/")// .setMethodName(HttpMethod.CONNECT.name())// .setUsePreemptiveAuth(true)// .parseProxyAuthenticateHeader(proxyAuthenticateHeaders.get(0))// .build(); } future.setReuseChannel(true); future.setConnectAllowed(true); Request nextRequest = new RequestBuilder(future.getRequest()).setHeaders(request.getHeaders()) .setRealm(newRealm).build(); requestSender.sendNextRequest(nextRequest, future); return true; } } return false; }
From source file:org.asynchttpclient.providers.netty.handler.HttpProtocol.java
License:Apache License
private boolean handleConnectOKAndExit(int statusCode, Realm realm, final Request request, HttpRequest httpRequest, HttpResponse response, final NettyResponseFuture<?> future, ProxyServer proxyServer, final Channel channel) throws IOException { if (statusCode == OK.code() && httpRequest.getMethod() == HttpMethod.CONNECT) { LOGGER.debug("Connected to {}:{}", proxyServer.getHost(), proxyServer.getPort()); if (future.isKeepAlive()) { future.attachChannel(channel, true); }/* w w w. j a v a 2 s . c om*/ try { URI requestURI = request.getURI(); String scheme = requestURI.getScheme(); LOGGER.debug("Connecting to proxy {} for scheme {}", proxyServer, scheme); String host = AsyncHttpProviderUtils.getHost(requestURI); int port = AsyncHttpProviderUtils.getPort(requestURI); channels.upgradeProtocol(channel.pipeline(), scheme, host, port); } catch (Throwable ex) { channels.abort(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.netty.request.NettyRequestFactory.java
License:Apache License
private String requestUri(URI uri, ProxyServer proxyServer, HttpMethod method) { if (method == HttpMethod.CONNECT) return AsyncHttpProviderUtils.getAuthority(uri); else if (proxyServer != null && !(isSecure(uri) && config.isUseRelativeURIsWithSSLProxies())) return uri.toString(); else if (uri.getRawQuery() != null) return uri.getRawPath() + "?" + uri.getRawQuery(); else//from ww w . j ava 2 s . c o m return uri.getRawPath(); }
From source file:org.asynchttpclient.providers.netty.request.NettyRequestFactory.java
License:Apache License
private String proxyAuthorizationHeader(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); if (isNTLM(auth)) { proxyAuthorization = auth.get(0); }/*from w w w.j a v a2s . c om*/ } else if (proxyServer != null && 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()); proxyAuthorization = "NTLM " + msg; } catch (NTLMEngineException e) { IOException ie = new IOException(); ie.initCause(e); throw ie; } } } else { proxyAuthorization = AuthenticatorUtils.computeBasicAuthentication(proxyServer); } } return proxyAuthorization; }
From source file:org.asynchttpclient.providers.netty.request.NettyRequestFactory.java
License:Apache License
private NettyBody body(Request request, HttpMethod method) throws IOException { NettyBody nettyBody = null;//ww w. j a v a 2 s. co 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.getStringData() != null) { nettyBody = new NettyByteArrayBody(request.getStringData().getBytes(bodyCharset)); } else if (request.getStreamData() != null) { nettyBody = new NettyInputStreamBody(request.getStreamData()); } else if (isNonEmpty(request.getParams())) { String contentType = null; if (!request.getHeaders().containsKey(HttpHeaders.Names.CONTENT_TYPE)) contentType = HttpHeaders.Values.APPLICATION_X_WWW_FORM_URLENCODED; nettyBody = new NettyByteArrayBody(computeBodyFromParams(request.getParams(), bodyCharset), contentType); } else if (request.getParts() != null) { 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; }