Java Code Examples for io.netty.handler.codec.http.HttpMethod#valueOf()

The following examples show how to use io.netty.handler.codec.http.HttpMethod#valueOf() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: HttpConversionUtil.java    From netty-4.1.22 with Apache License 2.0 6 votes vote down vote up
/**
 * Create a new object to contain the request data
 *
 * @param streamId The stream associated with the request
 * @param http2Headers The initial set of HTTP/2 headers to create the request with
 * @param alloc The {@link ByteBufAllocator} to use to generate the content of the message
 * @param validateHttpHeaders <ul>
 *        <li>{@code true} to validate HTTP headers in the http-codec</li>
 *        <li>{@code false} not to validate HTTP headers in the http-codec</li>
 *        </ul>
 * @return A new request object which represents headers/data
 * @throws Http2Exception see {@link #addHttp2ToHttpHeaders(int, Http2Headers, FullHttpMessage, boolean)}
 */
public static FullHttpRequest toFullHttpRequest(int streamId, Http2Headers http2Headers, ByteBufAllocator alloc,
                                            boolean validateHttpHeaders)
                throws Http2Exception {
    // HTTP/2 does not define a way to carry the version identifier that is included in the HTTP/1.1 request line.
    final CharSequence method = checkNotNull(http2Headers.method(),
            "method header cannot be null in conversion to HTTP/1.x");
    final CharSequence path = checkNotNull(http2Headers.path(),
            "path header cannot be null in conversion to HTTP/1.x");
    FullHttpRequest msg = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.valueOf(method
                    .toString()), path.toString(), alloc.buffer(), validateHttpHeaders);
    try {
        addHttp2ToHttpHeaders(streamId, http2Headers, msg, false);
    } catch (Http2Exception e) {
        msg.release();
        throw e;
    } catch (Throwable t) {
        msg.release();
        throw streamError(streamId, PROTOCOL_ERROR, t, "HTTP/2 to HTTP/1.x headers conversion error");
    }
    return msg;
}
 
Example 2
Source File: HttpDownUtil.java    From pdown-core with MIT License 6 votes vote down vote up
public static HttpRequestInfo buildRequest(String method, String url, Map<String, String> heads, String body)
    throws MalformedURLException {
  URL u = new URL(url);
  HttpHeadsInfo headsInfo = new HttpHeadsInfo();
  headsInfo.add("Host", u.getHost());
  headsInfo.add("Connection", "keep-alive");
  headsInfo.add("User-Agent", "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.75 Safari/537.36");
  headsInfo.add("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8");
  headsInfo.add("Referer", u.getHost());
  if (heads != null) {
    for (Entry<String, String> entry : heads.entrySet()) {
      headsInfo.set(entry.getKey(), entry.getValue() == null ? "" : entry.getValue());
    }
  }
  byte[] content = null;
  if (body != null && body.length() > 0) {
    content = body.getBytes();
    headsInfo.add("Content-Length", content.length);
  }
  HttpMethod httpMethod = StringUtil.isNullOrEmpty(method) ? HttpMethod.GET : HttpMethod.valueOf(method.toUpperCase());
  HttpRequestInfo requestInfo = new HttpRequestInfo(HttpVer.HTTP_1_1, httpMethod, u.getFile(), headsInfo, content);
  requestInfo.setRequestProto(parseRequestProto(u));
  return requestInfo;
}
 
Example 3
Source File: AsyncHttpClientHelperTest.java    From riposte with Apache License 2.0 6 votes vote down vote up
@Test
public void getRequestBuilder_delegates_to_helper_with_default_circuit_breaker_args() {
    // given
    String url = UUID.randomUUID().toString();
    HttpMethod method = HttpMethod.valueOf(UUID.randomUUID().toString());
    RequestBuilderWrapper rbwMock = mock(RequestBuilderWrapper.class);
    doReturn(rbwMock).when(helperSpy)
                     .getRequestBuilder(anyString(), any(HttpMethod.class), any(Optional.class), anyBoolean());

    // when
    RequestBuilderWrapper rbw = helperSpy.getRequestBuilder(url, method);

    // then
    verify(helperSpy).getRequestBuilder(url, method, Optional.empty(), false);
    assertThat(rbw).isSameAs(rbwMock);
}
 
Example 4
Source File: AllowAllTheThingsCORSFilterTest.java    From riposte with Apache License 2.0 6 votes vote down vote up
@DataProvider(value = {
    "OPTIONS    |   true",
    "GET        |   false",
    "POST       |   false",
    "PUT        |   false"
}, splitBy = "\\|")
@Test
public void filterRequestFirstChunkWithOptionalShortCircuitResponse_short_circuits_on_CORS_preflight_OPTIONS_request(String httpMethodString, boolean expectShortCircuit) {
    // given
    HttpMethod method = HttpMethod.valueOf(httpMethodString);
    doReturn(method).when(requestMock).getMethod();

    // when
    Pair<RequestInfo<?>, Optional<ResponseInfo<?>>> result = filter.filterRequestFirstChunkWithOptionalShortCircuitResponse(requestMock, ctxMock);

    // then
    if (expectShortCircuit) {
        assertThat(result).isNotNull();
        assertThat(result.getLeft()).isSameAs(requestMock);
        assertThat(result.getRight()).isPresent();
        assertThat(result.getRight().get().getHttpStatusCode()).isEqualTo(200);
    }
    else
        assertThat(result).isNull();
}
 
Example 5
Source File: AsyncHttpClientHelperTest.java    From riposte with Apache License 2.0 6 votes vote down vote up
@Test
public void getRequestBuilder_delegates_to_helper_with_default_circuit_breaker_args() {
    // given
    String url = UUID.randomUUID().toString();
    HttpMethod method = HttpMethod.valueOf(UUID.randomUUID().toString());
    RequestBuilderWrapper rbwMock = mock(RequestBuilderWrapper.class);
    doReturn(rbwMock).when(helperSpy)
                     .getRequestBuilder(anyString(), any(HttpMethod.class), any(Optional.class), anyBoolean());

    // when
    RequestBuilderWrapper rbw = helperSpy.getRequestBuilder(url, method);

    // then
    verify(helperSpy).getRequestBuilder(url, method, Optional.empty(), false);
    assertThat(rbw).isSameAs(rbwMock);
}
 
Example 6
Source File: CorsWrapperHandler.java    From ob1k with Apache License 2.0 5 votes vote down vote up
private static HttpMethod[] convertHeaders(final Set<String> sMethods) {
  HttpMethod[] methods = new HttpMethod[sMethods.size()];
  Iterator<String> iterator = sMethods.iterator();
  int i = 0;
  while (iterator.hasNext()) {
    //TODO Handle Invalid Method?
    methods[i++] =  HttpMethod.valueOf(iterator.next());
  }
  return methods;
}
 
Example 7
Source File: OriginResponseReceiver.java    From zuul with Apache License 2.0 5 votes vote down vote up
private HttpRequest buildOriginHttpRequest(final HttpRequestMessage zuulRequest) {
    final String method = zuulRequest.getMethod().toUpperCase();
    final String uri = pathAndQueryString(zuulRequest);

    customRequestProcessing(zuulRequest);

    final DefaultHttpRequest nettyReq = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.valueOf(method), uri, false);
    // Copy headers across.
    for (final Header h : zuulRequest.getHeaders().entries()) {
        nettyReq.headers().add(h.getKey(), h.getValue());
    }

    return nettyReq;
}
 
Example 8
Source File: SpdyHeaders.java    From netty4.0.27Learn with Apache License 2.0 5 votes vote down vote up
/**
 * Returns the {@link HttpMethod} represented by the HTTP method header.
 */
public static HttpMethod getMethod(int spdyVersion, SpdyHeadersFrame frame) {
    try {
        return HttpMethod.valueOf(frame.headers().get(HttpNames.METHOD));
    } catch (Exception e) {
        return null;
    }
}
 
Example 9
Source File: NettyHttpClientRequest.java    From cxf with Apache License 2.0 5 votes vote down vote up
public void createRequest(ByteBuf content) {
    this.request  =
        new DefaultFullHttpRequest(HttpVersion.HTTP_1_1,
                                   HttpMethod.valueOf(method),
                                   uri.getPath().toString(), content);
    // setup the default headers
    request.headers().set("Connection", "keep-alive");
    request.headers().set("Host", uri.getHost() + ":"
        + (uri.getPort() != -1 ? uri.getPort() : "http".equals(uri.getScheme()) ? 80 : 443));
}
 
Example 10
Source File: RiposteWingtipsNettyClientTagAdapterTest.java    From riposte with Apache License 2.0 5 votes vote down vote up
@Test
public void getRequestHttpMethod_works_as_expected() {
    // given
    HttpMethod expectedResult = HttpMethod.valueOf(UUID.randomUUID().toString());
    doReturn(expectedResult).when(requestMock).method();

    // when
    String result = adapterSpy.getRequestHttpMethod(requestMock);

    // then
    assertThat(result).isEqualTo(expectedResult.name());
}
 
Example 11
Source File: RiposteWingtipsServerTagAdapterTest.java    From riposte with Apache License 2.0 5 votes vote down vote up
@Test
public void getRequestHttpMethod_works_as_expected() {
    // given
    HttpMethod expectedResult = HttpMethod.valueOf(UUID.randomUUID().toString());
    doReturn(expectedResult).when(requestMock).getMethod();

    // when
    String result = adapterSpy.getRequestHttpMethod(requestMock);

    // then
    assertThat(result).isEqualTo(expectedResult.name());
}
 
Example 12
Source File: BrpcHttpObjectDecoder.java    From brpc-java with Apache License 2.0 5 votes vote down vote up
@Override
protected HttpMessage createMessage(String[] initialLine) throws Exception {

    return isDecodingRequest() ? new DefaultHttpRequest(
            HttpVersion.valueOf(initialLine[2]),
            HttpMethod.valueOf(initialLine[0]), initialLine[1], validateHeaders) :
            new DefaultHttpResponse(
                    HttpVersion.valueOf(initialLine[0]),
                    HttpResponseStatus.valueOf(Integer.parseInt(initialLine[1]), initialLine[2]), validateHeaders);
}
 
Example 13
Source File: HttpStreamDecoder.java    From netty-http2 with Apache License 2.0 4 votes vote down vote up
private StreamedHttpRequest createHttpRequest(HttpHeadersFrame httpHeadersFrame)
        throws Exception {
    // Create the first line of the request from the name/value pairs
    HttpMethod method = HttpMethod.valueOf(httpHeadersFrame.headers().get(":method"));
    String url = httpHeadersFrame.headers().get(":path");

    httpHeadersFrame.headers().remove(":method");
    httpHeadersFrame.headers().remove(":path");

    StreamedHttpRequest request = new StreamedHttpRequest(HttpVersion.HTTP_1_1, method, url);

    // Remove the scheme header
    httpHeadersFrame.headers().remove(":scheme");

    // Replace the SPDY host header with the HTTP host header
    String host = httpHeadersFrame.headers().get(":authority");
    httpHeadersFrame.headers().remove(":authority");
    httpHeadersFrame.headers().set("host", host);

    for (Map.Entry<String, String> e : httpHeadersFrame.headers()) {
        String name = e.getKey();
        String value = e.getValue();
        if (name.charAt(0) != ':') {
            request.headers().add(name, value);
        }
    }

    // Set the Stream-ID as a header
    request.headers().set("X-SPDY-Stream-ID", httpHeadersFrame.getStreamId());

    // The Connection and Keep-Alive headers are no longer valid
    HttpHeaders.setKeepAlive(request, true);

    // Transfer-Encoding header is not valid
    request.headers().remove(HttpHeaders.Names.TRANSFER_ENCODING);

    if (httpHeadersFrame.isLast()) {
        request.getContent().close();
        request.setDecoderResult(DecoderResult.SUCCESS);
    } else {
        request.setDecoderResult(DecoderResult.UNFINISHED);
    }

    return request;
}
 
Example 14
Source File: RequestAdapter.java    From aws-sdk-java-v2 with Apache License 2.0 4 votes vote down vote up
private static HttpMethod toNettyHttpMethod(SdkHttpMethod method) {
    return HttpMethod.valueOf(method.name());
}
 
Example 15
Source File: Http2CorsHandler.java    From xrpc with Apache License 2.0 4 votes vote down vote up
private HttpMethod requestMethod(Http2Headers headers, boolean isPreflight) {
  return isPreflight
      ? HttpMethod.valueOf(headers.get(HttpHeaderNames.ACCESS_CONTROL_REQUEST_METHOD).toString())
      : HttpMethod.OPTIONS;
}
 
Example 16
Source File: RequestBuilder.java    From hasor with Apache License 2.0 4 votes vote down vote up
public RequestObject buildObject() {
    return new RequestObject(HttpMethod.valueOf(this.httpMethod), this.headers, this.httpRequest, this.contentData);
}
 
Example 17
Source File: ClientHttp1ObjectEncoder.java    From armeria with Apache License 2.0 4 votes vote down vote up
private HttpObject convertHeaders(RequestHeaders headers, boolean endStream) {
    final String method = headers.method().name();
    final HttpRequest req = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.valueOf(method),
                                                   headers.path(), false);
    final io.netty.handler.codec.http.HttpHeaders nettyHeaders = req.headers();
    ArmeriaHttpUtil.toNettyHttp1ClientHeader(headers, nettyHeaders);

    if (!nettyHeaders.contains(HttpHeaderNames.USER_AGENT)) {
        nettyHeaders.add(HttpHeaderNames.USER_AGENT, HttpHeaderUtil.USER_AGENT.toString());
    }

    if (!nettyHeaders.contains(HttpHeaderNames.HOST)) {
        final InetSocketAddress remoteAddress = (InetSocketAddress) channel().remoteAddress();
        nettyHeaders.add(HttpHeaderNames.HOST, ArmeriaHttpUtil.authorityHeader(remoteAddress.getHostName(),
                                                                               remoteAddress.getPort(),
                                                                               protocol().defaultPort()));
    }

    if (endStream) {
        nettyHeaders.remove(HttpHeaderNames.TRANSFER_ENCODING);

        // Set or remove the 'content-length' header depending on request method.
        // See: https://tools.ietf.org/html/rfc7230#section-3.3.2
        //
        // > A user agent SHOULD send a Content-Length in a request message when
        // > no Transfer-Encoding is sent and the request method defines a meaning
        // > for an enclosed payload body.  For example, a Content-Length header
        // > field is normally sent in a POST request even when the value is 0
        // > (indicating an empty payload body).  A user agent SHOULD NOT send a
        // > Content-Length header field when the request message does not contain
        // > a payload body and the method semantics do not anticipate such a
        // > body.
        switch (method) {
            case "POST":
            case "PUT":
            case "PATCH":
                nettyHeaders.set(HttpHeaderNames.CONTENT_LENGTH, "0");
                break;
            default:
                nettyHeaders.remove(HttpHeaderNames.CONTENT_LENGTH);
        }
    } else if (HttpUtil.getContentLength(req, -1L) >= 0) {
        // Avoid the case where both 'content-length' and 'transfer-encoding' are set.
        nettyHeaders.remove(HttpHeaderNames.TRANSFER_ENCODING);
    } else {
        nettyHeaders.set(HttpHeaderNames.TRANSFER_ENCODING, HttpHeaderValues.CHUNKED);
    }
    return req;
}
 
Example 18
Source File: HttpRequestTemplate.java    From ribbon with Apache License 2.0 4 votes vote down vote up
public Builder<T>  withMethod(String method) {
    this.method = HttpMethod.valueOf(method);
    return this;
}
 
Example 19
Source File: FullHttp2Request.java    From xio with Apache License 2.0 4 votes vote down vote up
@Override
public HttpMethod method() {
  return HttpMethod.valueOf(delegate.method().toString());
}
 
Example 20
Source File: SpdyHttpDecoder.java    From netty-4.1.22 with Apache License 2.0 4 votes vote down vote up
private static FullHttpRequest createHttpRequest(SpdyHeadersFrame requestFrame, ByteBufAllocator alloc)
   throws Exception {
    // Create the first line of the request from the name/value pairs
    SpdyHeaders headers     = requestFrame.headers();
    HttpMethod  method      = HttpMethod.valueOf(headers.getAsString(METHOD));
    String      url         = headers.getAsString(PATH);
    HttpVersion httpVersion = HttpVersion.valueOf(headers.getAsString(VERSION));
    headers.remove(METHOD);
    headers.remove(PATH);
    headers.remove(VERSION);

    boolean release = true;
    ByteBuf buffer = alloc.buffer();
    try {
        FullHttpRequest req = new DefaultFullHttpRequest(httpVersion, method, url, buffer);

        // Remove the scheme header
        headers.remove(SCHEME);

        // Replace the SPDY host header with the HTTP host header
        CharSequence host = headers.get(HOST);
        headers.remove(HOST);
        req.headers().set(HttpHeaderNames.HOST, host);

        for (Map.Entry<CharSequence, CharSequence> e : requestFrame.headers()) {
            req.headers().add(e.getKey(), e.getValue());
        }

        // The Connection and Keep-Alive headers are no longer valid
        HttpUtil.setKeepAlive(req, true);

        // Transfer-Encoding header is not valid
        req.headers().remove(HttpHeaderNames.TRANSFER_ENCODING);
        release = false;
        return req;
    } finally {
        if (release) {
            buffer.release();
        }
    }
}