List of usage examples for io.netty.handler.codec.http HttpMethod GET
HttpMethod GET
To view the source code for io.netty.handler.codec.http HttpMethod GET.
Click Source Link
From source file:com.spotify.google.cloud.pubsub.client.Pubsub.java
License:Apache License
/** * Make a GET request.//from w ww . j ava 2 s . co m */ private <T> PubsubFuture<T> get(final String operation, final String path, final ResponseReader<T> responseReader) { return request(operation, HttpMethod.GET, path, responseReader); }
From source file:com.spotify.google.cloud.pubsub.client.Pubsub.java
License:Apache License
/** * Make an HTTP request.//from w w w . j a v a 2 s . c om */ private <T> PubsubFuture<T> request(final String operation, final HttpMethod method, final String path, final Object payload, final ResponseReader<T> responseReader) { final String uri = baseUri + path; final RequestBuilder builder = new RequestBuilder().setUrl(uri).setMethod(method.toString()) .setHeader("Authorization", "Bearer " + accessToken).setHeader(CONNECTION, KEEP_ALIVE) .setHeader("User-Agent", USER_AGENT); final long payloadSize; if (payload != NO_PAYLOAD) { final byte[] json = gzipJson(payload); payloadSize = json.length; builder.setHeader(CONTENT_ENCODING, GZIP); builder.setHeader(CONTENT_LENGTH, String.valueOf(json.length)); builder.setHeader(CONTENT_TYPE, APPLICATION_JSON_UTF8); builder.setBody(json); } else { builder.setHeader(CONTENT_LENGTH, String.valueOf(0)); payloadSize = 0; } final Request request = builder.build(); final RequestInfo requestInfo = RequestInfo.builder().operation(operation).method(method.toString()) .uri(uri).payloadSize(payloadSize).build(); final PubsubFuture<T> future = new PubsubFuture<>(requestInfo); client.executeRequest(request, new AsyncHandler<Void>() { private final ByteArrayOutputStream bytes = new ByteArrayOutputStream(); @Override public void onThrowable(final Throwable t) { future.fail(t); } @Override public State onBodyPartReceived(final HttpResponseBodyPart bodyPart) throws Exception { bytes.write(bodyPart.getBodyPartBytes()); return State.CONTINUE; } @Override public State onStatusReceived(final HttpResponseStatus status) { // Return null for 404'd GET & DELETE requests if (status.getStatusCode() == 404 && method == HttpMethod.GET || method == HttpMethod.DELETE) { future.succeed(null); return State.ABORT; } // Fail on non-2xx responses final int statusCode = status.getStatusCode(); if (!(statusCode >= 200 && statusCode < 300)) { future.fail(new RequestFailedException(status.getStatusCode(), status.getStatusText())); return State.ABORT; } if (responseReader == VOID) { future.succeed(null); return State.ABORT; } return State.CONTINUE; } @Override public State onHeadersReceived(final io.netty.handler.codec.http.HttpHeaders headers) { return State.CONTINUE; } @Override public Void onCompleted() throws Exception { if (future.isDone()) { return null; } try { future.succeed(responseReader.read(bytes.toByteArray())); } catch (Exception e) { future.fail(e); } return null; } }); return future; }
From source file:com.spotify.google.cloud.pubsub.client.Pubsub.java
License:Apache License
/** * Make an HTTP request using {@link java.net.HttpURLConnection}. *///from ww w .j ava 2 s . c om private <T> PubsubFuture<T> requestJavaNet(final String operation, final HttpMethod method, final String path, final Object payload, final ResponseReader<T> responseReader) { final HttpRequestFactory requestFactory = transport.createRequestFactory(); final String uri = baseUri + path; final HttpHeaders headers = new HttpHeaders(); final HttpRequest request; try { request = requestFactory.buildRequest(method.name(), new GenericUrl(URI.create(uri)), null); } catch (IOException e) { throw Throwables.propagate(e); } headers.setAuthorization("Bearer " + accessToken); headers.setUserAgent("Spotify"); final long payloadSize; if (payload != NO_PAYLOAD) { final byte[] json = gzipJson(payload); payloadSize = json.length; headers.setContentEncoding(GZIP.toString()); headers.setContentLength((long) json.length); headers.setContentType(APPLICATION_JSON_UTF8); request.setContent(new ByteArrayContent(APPLICATION_JSON_UTF8, json)); } else { payloadSize = 0; } request.setHeaders(headers); final RequestInfo requestInfo = RequestInfo.builder().operation(operation).method(method.toString()) .uri(uri).payloadSize(payloadSize).build(); final PubsubFuture<T> future = new PubsubFuture<>(requestInfo); executor.execute(() -> { final HttpResponse response; try { response = request.execute(); } catch (IOException e) { future.fail(e); return; } // Return null for 404'd GET & DELETE requests if (response.getStatusCode() == 404 && method == HttpMethod.GET || method == HttpMethod.DELETE) { future.succeed(null); return; } // Fail on non-2xx responses final int statusCode = response.getStatusCode(); if (!(statusCode >= 200 && statusCode < 300)) { future.fail(new RequestFailedException(response.getStatusCode(), response.getStatusMessage())); return; } if (responseReader == VOID) { future.succeed(null); return; } try { future.succeed(responseReader.read(ByteStreams.toByteArray(response.getContent()))); } catch (Exception e) { future.fail(e); } }); return future; }
From source file:com.springapp.mvc.netty.example.http.snoop.HttpSnoopClient.java
License:Apache License
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;/*from w ww . j a v a2 s . com*/ } 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(HttpHeaders.Names.HOST, host); request.headers().set(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.CLOSE); request.headers().set(HttpHeaders.Names.ACCEPT_ENCODING, HttpHeaders.Values.GZIP); // Set some example cookies. request.headers().set(HttpHeaders.Names.COOKIE, ClientCookieEncoder .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(); } }
From source file:com.springapp.mvc.netty.example.http.upload.HttpUploadClient.java
License:Apache License
/** * Standard usage of HTTP API in Netty without file Upload (get is not able to achieve File upload * due to limitation on request size).//w ww . j av a 2s .com * * @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(HttpHeaders.Names.HOST, host); headers.set(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.CLOSE); headers.set(HttpHeaders.Names.ACCEPT_ENCODING, HttpHeaders.Values.GZIP + ',' + HttpHeaders.Values.DEFLATE); headers.set(HttpHeaders.Names.ACCEPT_CHARSET, "ISO-8859-1,utf-8;q=0.7,*;q=0.7"); headers.set(HttpHeaders.Names.ACCEPT_LANGUAGE, "fr"); headers.set(HttpHeaders.Names.REFERER, uriSimple.toString()); headers.set(HttpHeaders.Names.USER_AGENT, "Netty Simple Http Client side"); headers.set(HttpHeaders.Names.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(HttpHeaders.Names.COOKIE, ClientCookieEncoder.encode(new DefaultCookie("my-cookie", "foo"), new DefaultCookie("another-cookie", "bar"))); // send request List<Entry<String, String>> entries = headers.entries(); channel.writeAndFlush(request); // Wait for the server to close the connection. channel.closeFuture().sync(); return entries; }
From source file:com.springapp.mvc.netty.example.spdy.client.SpdyClient.java
License:Apache License
public static void main(String[] args) throws Exception { // Configure SSL. final SslContext sslCtx = SslContextBuilder.forClient().trustManager(InsecureTrustManagerFactory.INSTANCE) .applicationProtocolConfig(/* w ww. ja v a 2s .c om*/ new ApplicationProtocolConfig(Protocol.NPN, SelectorFailureBehavior.CHOOSE_MY_LAST_PROTOCOL, SelectedListenerFailureBehavior.CHOOSE_MY_LAST_PROTOCOL, SelectedProtocol.SPDY_3_1.protocolName(), SelectedProtocol.HTTP_1_1.protocolName())) .build(); HttpResponseClientHandler httpResponseHandler = new HttpResponseClientHandler(); EventLoopGroup workerGroup = new NioEventLoopGroup(); try { Bootstrap b = new Bootstrap(); b.group(workerGroup); b.channel(NioSocketChannel.class); b.option(ChannelOption.SO_KEEPALIVE, true); b.remoteAddress(HOST, PORT); b.handler(new SpdyClientInitializer(sslCtx, httpResponseHandler)); // Start the client. Channel channel = b.connect().syncUninterruptibly().channel(); System.out.println("Connected to " + HOST + ':' + PORT); // Create a GET request. HttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, ""); request.headers().set(HttpHeaders.Names.HOST, HOST); request.headers().set(HttpHeaders.Names.ACCEPT_ENCODING, HttpHeaders.Values.GZIP); // Send the GET request. channel.writeAndFlush(request).sync(); // Waits for the complete HTTP response httpResponseHandler.queue().take().sync(); System.out.println("Finished SPDY HTTP GET"); // Wait until the connection is closed. channel.close().syncUninterruptibly(); } finally { if (workerGroup != null) { workerGroup.shutdownGracefully(); } } }
From source file:com.strategicgains.restexpress.plugin.cache.DateHeaderPostprocessorTest.java
License:Apache License
@Test public void shouldAddDateHeaderOnGet() throws ParseException { FullHttpRequest httpRequest = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, "/foo?param1=bar¶m2=blah&yada"); httpRequest.headers().add("Host", "testing-host"); Response response = new Response(); processor.process(new Request(httpRequest, null), response); assertTrue(response.hasHeaders());// w w w. ja va 2s . c o m String dateHeader = response.getHeader(HttpHeaders.Names.DATE); assertNotNull(dateHeader); Date dateValue = new HttpHeaderTimestampAdapter().parse(dateHeader); assertNotNull(dateValue); }
From source file:com.strategicgains.restexpress.plugin.route.RoutesMetadataPlugin.java
License:Apache License
@Override public RoutesMetadataPlugin register(RestExpress server) { if (isRegistered()) return this; super.register(server); RouteBuilder builder;/*from w w w. java2 s. c o m*/ builder = server.uri("/routes/metadata.{format}", controller).action("getAllRoutes", HttpMethod.GET) .name("all.routes.metadata"); routeBuilders.add(builder); builder = server.uri("/routes/{routeName}/metadata.{format}", controller) .action("getSingleRoute", HttpMethod.GET).name("single.route.metadata"); routeBuilders.add(builder); server.uri("/routes/console.html", controller).action("getConsole", HttpMethod.GET).noSerialization() .name("routes.metadata.console").format(Format.HTML); server.alias("service", ServerMetadata.class); server.alias("route", RouteMetadata.class); return this; }
From source file:com.strategicgains.restexpress.plugin.swagger.SwaggerPlugin.java
License:Apache License
@Override public SwaggerPlugin register(RestExpress server) { if (isRegistered()) return this; super.register(server); controller = new SwaggerController(server, apiVersion, swaggerVersion, isDefaultToHidden()); RouteBuilder resources = server.uri(urlPath, controller).action("readAll", HttpMethod.GET) .name("swagger.resources").format(Format.JSON); RouteBuilder apis = server.uri(urlPath + "/{path}", controller).method(HttpMethod.GET).name("swagger.apis") .format(Format.JSON); for (String flag : flags()) { resources.flag(flag);/*from ww w .java 2 s. c om*/ apis.flag(flag); } for (Entry<String, Object> entry : parameters().entrySet()) { resources.parameter(entry.getKey(), entry.getValue()); apis.parameter(entry.getKey(), entry.getValue()); } return this; }
From source file:com.strategicgains.restexpress.plugin.swagger.SwaggerPluginTest.java
License:Apache License
@BeforeClass public static void intialize() { RestAssured.port = PORT;//w w w .j ava2 s . c o m DummyController controller = new DummyController(); SERVER.setBaseUrl(BASE_URL); SERVER.uri("/", controller).action("health", HttpMethod.GET).name("root"); SERVER.uri("/anothers/{userId}", controller).action("readAnother", HttpMethod.GET); SERVER.uri("/users.{format}", controller).action("readAll", HttpMethod.GET) .action("options", HttpMethod.OPTIONS).method(HttpMethod.POST).name("Users Collection"); SERVER.uri("/users/{userId}.{format}", controller).method(HttpMethod.GET, HttpMethod.PUT, HttpMethod.DELETE) .action("options", HttpMethod.OPTIONS).name("Individual User"); SERVER.uri("/users/{userId}/orders.{format}", controller).action("readAll", HttpMethod.GET) .method(HttpMethod.POST).name("User Orders Collection"); SERVER.uri("/orders.{format}", controller).action("readAll", HttpMethod.GET).method(HttpMethod.POST) .name("Orders Collection"); SERVER.uri("/orders/{orderId}.{format}", controller) .method(HttpMethod.GET, HttpMethod.PUT, HttpMethod.DELETE).name("Individual Order"); SERVER.uri("/orders/{orderId}/items.{format}", controller).action("readAll", HttpMethod.GET) .method(HttpMethod.POST).name("Order Line-Items Collection"); SERVER.uri("/orders/{orderId}/items/{itemId}.{format}", controller) .method(HttpMethod.GET, HttpMethod.PUT, HttpMethod.DELETE).name("Individual Order Line-Item"); SERVER.uri("/products.{format}", controller).action("readAll", HttpMethod.GET).method(HttpMethod.POST) .name("Orders Collection"); SERVER.uri("/products/{orderId}.{format}", controller) .method(HttpMethod.GET, HttpMethod.PUT, HttpMethod.DELETE).name("Individual Order"); SERVER.uri("/health", controller).flag("somevalue").action("health", HttpMethod.GET).name("health"); SERVER.uri("/nicknametest", controller).method(HttpMethod.GET).name(" |nickName sh0uld_str1p-CHARS$. "); SERVER.uri("/annotations/{userId}/users", controller) .action("readWithApiOperationAnnotation", HttpMethod.GET).method(HttpMethod.GET) .name("Read with Annotations"); SERVER.uri("/annotations/hidden", controller).action("thisIsAHiddenAPI", HttpMethod.GET) .method(HttpMethod.GET).name("thisIsAHiddenAPI"); SERVER.uri("/annotations/{userId}", controller).action("updateWithApiResponse", HttpMethod.PUT) .method(HttpMethod.PUT).name("Update with Annotations"); SERVER.uri("/annotations/{userId}/users/list", controller) .action("createWithApiImplicitParams", HttpMethod.POST).method(HttpMethod.POST) .name("Create with Implicit Params"); SERVER.uri("/annotations/{userId}/users/newlist", controller).action("createWithApiParam", HttpMethod.POST) .method(HttpMethod.POST).name("Create with Api Param"); SERVER.uri("/annotations/{userId}/users/list2", controller) .action("createWithApiModelRequest", HttpMethod.POST).method(HttpMethod.POST) .name("Create with Implicit Params"); new SwaggerPlugin().apiVersion("1.0").swaggerVersion("1.2").flag("flag1").flag("flag2") .parameter("parm1", "value1").parameter("parm2", "value2").register(SERVER); SERVER.bind(PORT); }