Search in sources :

Example 21 with Method

use of org.apache.hc.core5.http.Method in project httpcomponents-core by apache.

the class DefaultH2RequestConverter method convert.

@Override
public List<Header> convert(final HttpRequest message) throws HttpException {
    if (TextUtils.isBlank(message.getMethod())) {
        throw new ProtocolException("Request method is empty");
    }
    final boolean optionMethod = Method.CONNECT.name().equalsIgnoreCase(message.getMethod());
    if (optionMethod) {
        if (message.getAuthority() == null) {
            throw new ProtocolException("CONNECT request authority is not set");
        }
        if (message.getPath() != null) {
            throw new ProtocolException("CONNECT request path must be null");
        }
    } else {
        if (TextUtils.isBlank(message.getScheme())) {
            throw new ProtocolException("Request scheme is not set");
        }
        if (TextUtils.isBlank(message.getPath())) {
            throw new ProtocolException("Request path is not set");
        }
    }
    final List<Header> headers = new ArrayList<>();
    headers.add(new BasicHeader(H2PseudoRequestHeaders.METHOD, message.getMethod(), false));
    if (optionMethod) {
        headers.add(new BasicHeader(H2PseudoRequestHeaders.AUTHORITY, message.getAuthority(), false));
    } else {
        headers.add(new BasicHeader(H2PseudoRequestHeaders.SCHEME, message.getScheme(), false));
        if (message.getAuthority() != null) {
            headers.add(new BasicHeader(H2PseudoRequestHeaders.AUTHORITY, message.getAuthority(), false));
        }
        headers.add(new BasicHeader(H2PseudoRequestHeaders.PATH, message.getPath(), false));
    }
    for (final Iterator<Header> it = message.headerIterator(); it.hasNext(); ) {
        final Header header = it.next();
        final String name = header.getName();
        final String value = header.getValue();
        if (name.startsWith(":")) {
            throw new ProtocolException("Header name '%s' is invalid", name);
        }
        if (name.equalsIgnoreCase(HttpHeaders.CONNECTION) || name.equalsIgnoreCase(HttpHeaders.KEEP_ALIVE) || name.equalsIgnoreCase(HttpHeaders.PROXY_CONNECTION) || name.equalsIgnoreCase(HttpHeaders.TRANSFER_ENCODING) || name.equalsIgnoreCase(HttpHeaders.HOST) || name.equalsIgnoreCase(HttpHeaders.UPGRADE)) {
            throw new ProtocolException("Header '%s: %s' is illegal for HTTP/2 messages", header.getName(), header.getValue());
        }
        if (name.equalsIgnoreCase(HttpHeaders.TE) && !value.equalsIgnoreCase("trailers")) {
            throw new ProtocolException("Header '%s: %s' is illegal for HTTP/2 messages", header.getName(), header.getValue());
        }
        headers.add(new BasicHeader(TextUtils.toLowerCase(name), value));
    }
    return headers;
}
Also used : ProtocolException(org.apache.hc.core5.http.ProtocolException) Header(org.apache.hc.core5.http.Header) BasicHeader(org.apache.hc.core5.http.message.BasicHeader) ArrayList(java.util.ArrayList) BasicHeader(org.apache.hc.core5.http.message.BasicHeader)

Example 22 with Method

use of org.apache.hc.core5.http.Method in project httpcomponents-core by apache.

the class DefaultConnectionReuseStrategy method keepAlive.

// see interface ConnectionReuseStrategy
@Override
public boolean keepAlive(final HttpRequest request, final HttpResponse response, final HttpContext context) {
    Args.notNull(response, "HTTP response");
    if (request != null) {
        final Iterator<String> ti = new BasicTokenIterator(request.headerIterator(HttpHeaders.CONNECTION));
        while (ti.hasNext()) {
            final String token = ti.next();
            if (HeaderElements.CLOSE.equalsIgnoreCase(token)) {
                return false;
            }
        }
    }
    // returns content as part of a HTTP 204 response.
    if (response.getCode() == HttpStatus.SC_NO_CONTENT) {
        final Header clh = response.getFirstHeader(HttpHeaders.CONTENT_LENGTH);
        if (clh != null) {
            try {
                final long contentLen = Long.parseLong(clh.getValue());
                if (contentLen > 0) {
                    return false;
                }
            } catch (final NumberFormatException ex) {
            // fall through
            }
        }
        if (response.containsHeader(HttpHeaders.TRANSFER_ENCODING)) {
            return false;
        }
    }
    // Check for a self-terminating entity. If the end of the entity will
    // be indicated by closing the connection, there is no keep-alive.
    final Header teh = response.getFirstHeader(HttpHeaders.TRANSFER_ENCODING);
    if (teh != null) {
        if (!HeaderElements.CHUNKED_ENCODING.equalsIgnoreCase(teh.getValue())) {
            return false;
        }
    } else {
        final String method = request != null ? request.getMethod() : null;
        if (MessageSupport.canResponseHaveBody(method, response) && response.countHeaders(HttpHeaders.CONTENT_LENGTH) != 1) {
            return false;
        }
    }
    // Check for the "Connection" header. If that is absent, check for
    // the "Proxy-Connection" header. The latter is an unspecified and
    // broken but unfortunately common extension of HTTP.
    Iterator<Header> headerIterator = response.headerIterator(HttpHeaders.CONNECTION);
    if (!headerIterator.hasNext()) {
        headerIterator = response.headerIterator("Proxy-Connection");
    }
    final ProtocolVersion ver = response.getVersion() != null ? response.getVersion() : context.getProtocolVersion();
    if (headerIterator.hasNext()) {
        if (ver.greaterEquals(HttpVersion.HTTP_1_1)) {
            final Iterator<String> it = new BasicTokenIterator(headerIterator);
            while (it.hasNext()) {
                final String token = it.next();
                if (HeaderElements.CLOSE.equalsIgnoreCase(token)) {
                    return false;
                }
            }
            return true;
        }
        final Iterator<String> it = new BasicTokenIterator(headerIterator);
        while (it.hasNext()) {
            final String token = it.next();
            if (HeaderElements.KEEP_ALIVE.equalsIgnoreCase(token)) {
                return true;
            }
        }
        return false;
    }
    return ver.greaterEquals(HttpVersion.HTTP_1_1);
}
Also used : Header(org.apache.hc.core5.http.Header) ProtocolVersion(org.apache.hc.core5.http.ProtocolVersion) BasicTokenIterator(org.apache.hc.core5.http.message.BasicTokenIterator)

Example 23 with Method

use of org.apache.hc.core5.http.Method in project httpcomponents-core by apache.

the class RequestTargetHost method process.

@Override
public void process(final HttpRequest request, final EntityDetails entity, final HttpContext context) throws HttpException, IOException {
    Args.notNull(request, "HTTP request");
    Args.notNull(context, "HTTP context");
    final ProtocolVersion ver = context.getProtocolVersion();
    final String method = request.getMethod();
    if (Method.CONNECT.isSame(method) && ver.lessEquals(HttpVersion.HTTP_1_0)) {
        return;
    }
    if (!request.containsHeader(HttpHeaders.HOST)) {
        URIAuthority authority = request.getAuthority();
        if (authority == null) {
            if (ver.lessEquals(HttpVersion.HTTP_1_0)) {
                return;
            }
            throw new ProtocolException("Target host is unknown");
        }
        if (authority.getUserInfo() != null) {
            authority = new URIAuthority(authority.getHostName(), authority.getPort());
        }
        request.addHeader(HttpHeaders.HOST, authority);
    }
}
Also used : ProtocolException(org.apache.hc.core5.http.ProtocolException) URIAuthority(org.apache.hc.core5.net.URIAuthority) ProtocolVersion(org.apache.hc.core5.http.ProtocolVersion)

Example 24 with Method

use of org.apache.hc.core5.http.Method in project httpcomponents-core by apache.

the class RequestContent method process.

@Override
public void process(final HttpRequest request, final EntityDetails entity, final HttpContext context) throws HttpException, IOException {
    Args.notNull(request, "HTTP request");
    final String method = request.getMethod();
    if (Method.TRACE.isSame(method) && entity != null) {
        throw new ProtocolException("TRACE request may not enclose an entity");
    }
    if (this.overwrite) {
        request.removeHeaders(HttpHeaders.TRANSFER_ENCODING);
        request.removeHeaders(HttpHeaders.CONTENT_LENGTH);
    } else {
        if (request.containsHeader(HttpHeaders.TRANSFER_ENCODING)) {
            throw new ProtocolException("Transfer-encoding header already present");
        }
        if (request.containsHeader(HttpHeaders.CONTENT_LENGTH)) {
            throw new ProtocolException("Content-Length header already present");
        }
    }
    if (entity != null) {
        final ProtocolVersion ver = context.getProtocolVersion();
        // Must specify a transfer encoding or a content length
        if (entity.isChunked() || entity.getContentLength() < 0) {
            if (ver.lessEquals(HttpVersion.HTTP_1_0)) {
                throw new ProtocolException("Chunked transfer encoding not allowed for " + ver);
            }
            request.addHeader(HttpHeaders.TRANSFER_ENCODING, HeaderElements.CHUNKED_ENCODING);
            MessageSupport.addTrailerHeader(request, entity);
        } else {
            request.addHeader(HttpHeaders.CONTENT_LENGTH, Long.toString(entity.getContentLength()));
        }
        MessageSupport.addContentTypeHeader(request, entity);
        MessageSupport.addContentEncodingHeader(request, entity);
    }
}
Also used : ProtocolException(org.apache.hc.core5.http.ProtocolException) ProtocolVersion(org.apache.hc.core5.http.ProtocolVersion)

Example 25 with Method

use of org.apache.hc.core5.http.Method in project httpcomponents-core by apache.

the class URIBuilder method setParameter.

/**
 * Sets parameter of URI query overriding existing value if set. The parameter name and value
 * are expected to be unescaped and may contain non ASCII characters.
 * <p>
 * Please note query parameters and custom query component are mutually exclusive. This method
 * will remove custom query if present.
 * </p>
 *
 * @return this.
 */
public URIBuilder setParameter(final String param, final String value) {
    if (this.queryParams == null) {
        this.queryParams = new ArrayList<>();
    }
    if (!this.queryParams.isEmpty()) {
        this.queryParams.removeIf(nvp -> nvp.getName().equals(param));
    }
    this.queryParams.add(new BasicNameValuePair(param, value));
    this.encodedQuery = null;
    this.encodedSchemeSpecificPart = null;
    this.query = null;
    return this;
}
Also used : BasicNameValuePair(org.apache.hc.core5.http.message.BasicNameValuePair)

Aggregations

Header (org.apache.hc.core5.http.Header)38 BasicHeader (org.apache.hc.core5.http.message.BasicHeader)29 Test (org.junit.jupiter.api.Test)29 CloseableHttpResponse (org.apache.hc.client5.http.impl.classic.CloseableHttpResponse)16 IOException (java.io.IOException)15 URI (java.net.URI)14 URISyntaxException (java.net.URISyntaxException)14 Map (java.util.Map)14 HttpEntity (org.apache.hc.core5.http.HttpEntity)13 HttpHost (org.apache.hc.core5.http.HttpHost)12 StringEntity (org.apache.hc.core5.http.io.entity.StringEntity)10 ContentType (org.apache.hc.core5.http.ContentType)9 BasicHttpRequest (org.apache.hc.core5.http.message.BasicHttpRequest)9 HttpRequest (org.apache.hc.core5.http.HttpRequest)8 HashMap (java.util.HashMap)7 HttpGet (org.apache.hc.client5.http.classic.methods.HttpGet)7 ProtocolVersion (org.apache.hc.core5.http.ProtocolVersion)7 SocketTimeoutException (java.net.SocketTimeoutException)6 ArrayList (java.util.ArrayList)6 BasicNameValuePair (org.apache.hc.core5.http.message.BasicNameValuePair)6