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.providers.netty4.request.NettyRequestFactory.java
License:Open Source 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 w w w . ja v a 2 s . c o m 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 (method != HttpMethod.CONNECT) { // assign headers as configured on request for (Entry<String, List<String>> header : request.getHeaders()) { headers.set(header.getKey(), header.getValue()); } if (isNonEmpty(request.getCookies())) headers.set(HttpHeaders.Names.COOKIE, CookieEncoder.encode(request.getCookies())); if (config.isCompressionEnforced() && !headers.contains(HttpHeaders.Names.ACCEPT_ENCODING)) headers.set(HttpHeaders.Names.ACCEPT_ENCODING, GZIP_DEFLATE); } if (body != null) { if (body.getContentLength() < 0) headers.set(HttpHeaders.Names.TRANSFER_ENCODING, HttpHeaders.Values.CHUNKED); else headers.set(HttpHeaders.Names.CONTENT_LENGTH, body.getContentLength()); if (body.getContentType() != null) headers.set(HttpHeaders.Names.CONTENT_TYPE, body.getContentType()); } // connection header and friends boolean webSocket = isWebSocket(uri.getScheme()); if (method != HttpMethod.CONNECT && webSocket) { headers.set(HttpHeaders.Names.UPGRADE, HttpHeaders.Values.WEBSOCKET)// .set(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.UPGRADE)// .set(HttpHeaders.Names.ORIGIN, "http://" + uri.getHost() + ":" + (uri.getPort() == -1 ? isSecure(uri.getScheme()) ? 443 : 80 : uri.getPort()))// .set(HttpHeaders.Names.SEC_WEBSOCKET_KEY, getKey())// .set(HttpHeaders.Names.SEC_WEBSOCKET_VERSION, "13"); } else if (!headers.contains(HttpHeaders.Names.CONNECTION)) { headers.set(HttpHeaders.Names.CONNECTION, keepAliveHeaderValue(config)); } if (!headers.contains(HttpHeaders.Names.HOST)) headers.set(HttpHeaders.Names.HOST, hostHeader(request, uri)); Realm realm = request.getRealm() != null ? request.getRealm() : config.getRealm(); // don't override authorization but append addAuthorizationHeader(headers, systematicAuthorizationHeader(request, uri, proxyServer, realm)); setProxyAuthorizationHeader(headers, systematicProxyAuthorizationHeader(request, proxyServer, method)); // Add default accept headers if (!headers.contains(HttpHeaders.Names.ACCEPT)) headers.set(HttpHeaders.Names.ACCEPT, "*/*"); // Add default user agent if (!headers.contains(HttpHeaders.Names.USER_AGENT) && config.getUserAgent() != null) headers.set(HttpHeaders.Names.USER_AGENT, config.getUserAgent()); return nettyRequest; }
From source file:org.asynchttpclient.providers.netty4.request.NettyRequestSender.java
License:Open Source 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"); Uri uri = request.getUri();//from ww w . ja v a 2s .c o m // FIXME really useful? Why not do this check when building the request? if (uri.getScheme().startsWith(WEBSOCKET) && !validateWebSocketRequest(request, asyncHandler)) throw new IOException("WebSocket method must be a GET"); ProxyServer proxyServer = getProxyServer(config, request); boolean resultOfAConnect = future != null && future.getNettyRequest() != null && future.getNettyRequest().getHttpRequest().getMethod() == HttpMethod.CONNECT; boolean useProxy = proxyServer != null && !resultOfAConnect; if (useProxy && useProxyConnect(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.netty4.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;//from w ww .ja v a 2 s .c om try { if (handler instanceof TransferCompletionHandler) configureTransferAdapter(handler, httpRequest); if (!future.isHeadersAlreadyWrittenOnContinue()) { if (future.getAsyncHandler() instanceof AsyncHandlerExtensions) AsyncHandlerExtensions.class.cast(future.getAsyncHandler()).onSendRequest(nettyRequest); channel.writeAndFlush(httpRequest, channel.newProgressivePromise()) .addListener(new ProgressListener(config, future.getAsyncHandler(), future, true, 0L)); } if (!future.isDontWriteBodyBecauseExpectContinue() && !httpRequest.getMethod().equals(HttpMethod.CONNECT) && nettyRequest.getBody() != null) nettyRequest.getBody().write(channel, future, config); // don't bother scheduling timeouts if channel became invalid if (Channels.isChannelValid(channel)) scheduleTimeouts(future); } catch (Throwable t) { LOGGER.error("Can't write request", t); Channels.silentlyCloseChannel(channel); } }
From source file:org.elasticsearch.http.nio.NioHttpRequest.java
License:Apache License
@Override public RestRequest.Method method() { HttpMethod httpMethod = request.method(); if (httpMethod == HttpMethod.GET) return RestRequest.Method.GET; if (httpMethod == HttpMethod.POST) return RestRequest.Method.POST; if (httpMethod == HttpMethod.PUT) return RestRequest.Method.PUT; if (httpMethod == HttpMethod.DELETE) return RestRequest.Method.DELETE; if (httpMethod == HttpMethod.HEAD) { return RestRequest.Method.HEAD; }//from w w w. ja va 2s. co m if (httpMethod == HttpMethod.OPTIONS) { return RestRequest.Method.OPTIONS; } if (httpMethod == HttpMethod.PATCH) { return RestRequest.Method.PATCH; } if (httpMethod == HttpMethod.TRACE) { return RestRequest.Method.TRACE; } if (httpMethod == HttpMethod.CONNECT) { return RestRequest.Method.CONNECT; } throw new IllegalArgumentException("Unexpected http method: " + httpMethod); }
From source file:org.shelloid.vpt.agent.App.java
License:Open Source License
public void initClient(final String key, final String secret, final ICallback callback) throws Exception { final String host = Configurations.get(Configurations.ConfigParams.SERVER_IP); final int port = Integer.parseInt(Configurations.get(Configurations.ConfigParams.SERVER_PORT)); final boolean useProxy = Boolean.parseBoolean(Configurations.get(Configurations.ConfigParams.USE_PROXY)); final URI uri = new URI("wss://" + host + ":" + port + Configurations.WEBSOCKET_PATH); int proxPort; String proxyHost;/*from w w w . ja va2 s.c om*/ String proxyUserName; String proxyPassword; Platform.shelloidLogger.warn("Client authenticating Authenticating with " + key); final SslContext sslCtx = SslContext.newClientContext(ShelloidTrustManagerFactory.INSTANCE); group = new NioEventLoopGroup(); Bootstrap b = new Bootstrap(); b.group(group).channel(NioSocketChannel.class).handler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel ch) { ChannelPipeline p = ch.pipeline(); if (useProxy) { p.addLast(new HttpClientCodec(), new HttpObjectAggregator(ShelloidUtil.getMaxFrameSize()), new ProxyClient(uri, key, secret, callback)); } else { preparePipeLine(ch, key, secret, callback, uri, sslCtx); } } }); if (useProxy) { try { proxPort = Integer.parseInt(Configurations.get(Configurations.ConfigParams.PROXY_PORT) + ""); proxyHost = Configurations.get(Configurations.ConfigParams.PROXY_SERVER) + ""; proxyUserName = Configurations.get(Configurations.ConfigParams.PROXY_USERNAME) + ""; proxyPassword = Configurations.get(Configurations.ConfigParams.PROXY_PASSWORD) + ""; Platform.shelloidLogger.warn("Using proxy server " + proxyHost + ":" + proxPort); Channel ch = b.connect(proxyHost, proxPort).sync().channel(); HttpRequest request = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.CONNECT, uri.getHost() + ":" + uri.getPort()); request.headers().add("Host", uri.getHost() + ":" + uri.getPort()); request.headers().add("Proxy-Authorization", "basic " + new String(Base64.encodeBase64((proxyUserName + ":" + proxyPassword).getBytes()))); ch.writeAndFlush(request).sync(); } catch (NumberFormatException ex) { Configurations.put(Configurations.ConfigParams.USE_PROXY, false + ""); throw new Exception( "Invalid proxy port number: " + Configurations.get(Configurations.ConfigParams.PROXY_PORT) + "\nRetrying without proxy support."); } } else { b.connect(uri.getHost(), uri.getPort()).sync(); } }
From source file:org.thingsplode.synapse.endpoint.handlers.HttpRequestHandler.java
License:Apache License
@Override protected void channelRead0(ChannelHandlerContext ctx, FullHttpRequest httpRequest) throws Exception { //todo: support for API keys ///endpoints/json?api_key=565656 try {// w w w . jav a 2 s . co m // Handle a bad request. if (!httpRequest.decoderResult().isSuccess()) { HttpResponseHandler.sendError(ctx, HttpResponseStatus.BAD_REQUEST, "Could not decode request.", httpRequest); return; } if (httpRequest.method().equals(HttpMethod.HEAD) || httpRequest.method().equals(HttpMethod.PATCH) || httpRequest.method().equals(HttpMethod.TRACE) || httpRequest.method().equals(HttpMethod.CONNECT) || httpRequest.method().equals(HttpMethod.OPTIONS)) { HttpResponseHandler.sendError(ctx, HttpResponseStatus.FORBIDDEN, "Method forbidden (The following are not supported: HEAD, PATCH, TRACE, CONNECT, OPTIONS).", httpRequest); return; } //check websocket upgrade request String upgradeHeader = httpRequest.headers().get(HttpHeaderNames.UPGRADE); if (!Util.isEmpty(upgradeHeader) && UPGRADE_TO_WEBSOCKET.equalsIgnoreCase(upgradeHeader)) { //case websocket upgrade request is detected -> Prepare websocket handshake upgradeToWebsocket(ctx, httpRequest); return; } else { //case simple http request Request request = new Request(prepareHeader(ctx, httpRequest)); //no information about the object type / it will be processed in a later stage //todo: with requestbodytype header value early deserialization would be possible, however not beneficial in routing cases request.setBody(httpRequest.content()); ctx.fireChannelRead(request); } } catch (Exception ex) { logger.error("Channel read error: " + ex.getMessage(), ex); HttpResponseHandler.sendError(ctx, HttpResponseStatus.INTERNAL_SERVER_ERROR, ex.getClass().getSimpleName() + ": " + ex.getMessage(), httpRequest); } }
From source file:org.wso2.carbon.transport.http.netty.common.Util.java
License:Open Source License
/** * Prepare response message with Transfer-Encoding/Content-Length. * * @param cMsg Carbon message./*from ww w . j a v a 2s .c o m*/ * @param requestDataHolder Requested data holder. */ public static void setupTransferEncodingForResponse(HTTPCarbonMessage cMsg, RequestDataHolder requestDataHolder) { // 1. Remove Transfer-Encoding and Content-Length as per rfc7230#section-3.3.1 int statusCode = Util.getIntValue(cMsg, Constants.HTTP_STATUS_CODE, 200); String httpMethod = requestDataHolder.getHttpMethod(); if (statusCode == 204 || statusCode >= 100 && statusCode < 200 || (HttpMethod.CONNECT.name().equals(httpMethod) && statusCode >= 200 && statusCode < 300)) { cMsg.removeHeader(Constants.HTTP_TRANSFER_ENCODING); cMsg.removeHeader(Constants.HTTP_CONTENT_LENGTH); return; } // 2. Check for transfer encoding header is set in the request // As per RFC 2616, Section 4.4, Content-Length must be ignored if Transfer-Encoding header // is present and its value not equal to 'identity' String requestTransferEncodingHeader = requestDataHolder.getTransferEncodingHeader(); if (requestTransferEncodingHeader != null && !Constants.HTTP_TRANSFER_ENCODING_IDENTITY.equalsIgnoreCase(requestTransferEncodingHeader)) { cMsg.setHeader(Constants.HTTP_TRANSFER_ENCODING, requestTransferEncodingHeader); cMsg.removeHeader(Constants.HTTP_CONTENT_LENGTH); return; } // 3. Check for request Content-Length header String requestContentLength = requestDataHolder.getContentLengthHeader(); if (requestContentLength != null && (cMsg.isAlreadyRead() || (cMsg.getHeader(Constants.HTTP_CONTENT_LENGTH) == null))) { Util.prepareBuiltMessageForTransfer(cMsg); if (!cMsg.isEmpty()) { int contentLength = cMsg.getFullMessageLength(); if (contentLength > 0) { cMsg.setHeader(Constants.HTTP_CONTENT_LENGTH, String.valueOf(contentLength)); } cMsg.removeHeader(Constants.HTTP_TRANSFER_ENCODING); return; } } // 4. If request doesn't have Transfer-Encoding or Content-Length header look for response properties if (cMsg.getHeader(Constants.HTTP_TRANSFER_ENCODING) != null) { cMsg.getHeaders().remove(Constants.HTTP_CONTENT_LENGTH); // remove Content-Length if present } else if (cMsg.isAlreadyRead() || (cMsg.getHeader(Constants.HTTP_CONTENT_LENGTH) == null)) { Util.prepareBuiltMessageForTransfer(cMsg); if (!cMsg.isEmpty()) { int contentLength = cMsg.getFullMessageLength(); cMsg.setHeader(Constants.HTTP_CONTENT_LENGTH, String.valueOf(contentLength)); } else { cMsg.setHeader(Constants.HTTP_CONTENT_LENGTH, String.valueOf(0)); } } }