List of usage examples for io.netty.handler.codec.http HttpMethod toString
@Override
public String toString()
From source file:com.github.ambry.rest.HealthCheckHandlerTest.java
License:Open Source License
/** * Does a test to see that a non health check request results in expected responses * @param httpMethod the {@link HttpMethod} for the request. * @param uri Uri to be used during the request * @throws IOException//from w w w. ja v a2 s. co m */ private void testNonHealthCheckRequest(HttpMethod httpMethod, String uri) throws IOException { EmbeddedChannel channel = createChannel(); HttpRequest request = RestTestUtils.createRequest(httpMethod, uri, null); FullHttpResponse response = sendRequestAndGetResponse(channel, request); assertEquals("Unexpected response status", HttpResponseStatus.OK, response.getStatus()); assertEquals("Unexpected content", httpMethod.toString(), RestTestUtils.getContentString(response)); channel.close(); }
From source file:com.spotify.google.cloud.pubsub.client.Pubsub.java
License:Apache License
/** * Make an HTTP request./* w ww. ja va2 s . com*/ */ 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}. */// w w w . j a v a2s. co m 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:uapi.web.http.netty.internal.NettyHttpRequest.java
License:Open Source License
NettyHttpRequest(final ILogger logger, final HttpRequest httpRequest) { this._logger = logger; this._request = httpRequest; HttpHeaders headers = this._request.headers(); Looper.from(headers.iteratorAsString()) .foreach(entry -> this._headers.put(entry.getKey().toLowerCase(), entry.getValue())); this._uri = this._request.uri(); QueryStringDecoder queryStringDecoder = new QueryStringDecoder(this._uri); Map<String, List<String>> params = queryStringDecoder.parameters(); Looper.from(params.entrySet()).foreach(entry -> this._params.put(entry.getKey(), entry.getValue())); HttpVersion version = this._request.protocolVersion(); if (HttpVersion.HTTP_1_0.equals(version)) { this._version = uapi.web.http.HttpVersion.V_1_0; } else if (HttpVersion.HTTP_1_1.equals(version)) { this._version = uapi.web.http.HttpVersion.V_1_1; } else {// w w w .j a va2s .c o m throw new KernelException("Unsupported Http version - {}", version); } HttpMethod method = this._request.method(); if (HttpMethod.GET.equals(method)) { this._method = uapi.web.http.HttpMethod.GET; } else if (HttpMethod.PUT.equals(method)) { this._method = uapi.web.http.HttpMethod.PUT; } else if (HttpMethod.POST.equals(method)) { this._method = uapi.web.http.HttpMethod.POST; } else if (HttpMethod.PATCH.equals(method)) { this._method = uapi.web.http.HttpMethod.PATCH; } else if (HttpMethod.DELETE.equals(method)) { this._method = uapi.web.http.HttpMethod.DELETE; } else { throw new KernelException("Unsupported http method {}", method.toString()); } // Decode content type String contentTypeString = this._headers.get(HttpHeaderNames.CONTENT_TYPE.toString()); if (contentTypeString == null) { this._conentType = ContentType.TEXT; this._charset = Charset.forName("UTF-8"); } else { String[] contentTypeInfo = contentTypeString.split(";"); if (contentTypeInfo.length < 0) { this._conentType = ContentType.TEXT; this._charset = CharsetUtil.UTF_8; } else if (contentTypeInfo.length == 1) { this._conentType = ContentType.parse(contentTypeInfo[0].trim()); this._charset = CharsetUtil.UTF_8; } else { this._conentType = ContentType.parse(contentTypeInfo[0].trim()); this._charset = Looper.from(contentTypeInfo).map(info -> info.split("=")) .filter(kv -> kv.length == 2).filter(kv -> kv[0].trim().equalsIgnoreCase("charset")) .map(kv -> kv[1].trim()).map(Charset::forName).first(CharsetUtil.UTF_8); } } }