Search in sources :

Example 1 with ProtocolVersion

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

the class TestTestingFramework method changeProtocolVersion.

@Test
public void changeProtocolVersion() throws Exception {
    final ClientTestingAdapter adapter = new ClassicTestClientTestingAdapter() {

        @Override
        public Map<String, Object> execute(final String defaultURI, final Map<String, Object> request, final TestingFrameworkRequestHandler requestHandler, final Map<String, Object> responseExpectations) throws TestingFrameworkException {
            // change the request from what is expected.
            final ProtocolVersion protocolVersion = (ProtocolVersion) request.get(PROTOCOL_VERSION);
            Assertions.assertNotNull(protocolVersion);
            request.put(PROTOCOL_VERSION, HttpVersion.HTTP_1_0);
            return super.execute(defaultURI, request, requestHandler, responseExpectations);
        }
    };
    final TestingFramework framework = newFrameworkAndSetAdapter(adapter);
    framework.addTest();
    Assertions.assertThrows(TestingFrameworkException.class, () -> framework.runTests());
}
Also used : ProtocolVersion(org.apache.hc.core5.http.ProtocolVersion) HashMap(java.util.HashMap) Map(java.util.Map) Test(org.junit.jupiter.api.Test)

Example 2 with ProtocolVersion

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

the class ClassicTestClientAdapter method execute.

/**
 * {@inheritDoc}
 */
@Override
public Map<String, Object> execute(final String defaultURI, final Map<String, Object> request) throws Exception {
    // check the request for missing items.
    if (defaultURI == null) {
        throw new HttpException("defaultURL cannot be null");
    }
    if (request == null) {
        throw new HttpException("request cannot be null");
    }
    if (!request.containsKey(PATH)) {
        throw new HttpException("Request path should be set.");
    }
    if (!request.containsKey(METHOD)) {
        throw new HttpException("Request method should be set.");
    }
    final Timeout timeout;
    if (request.containsKey(TIMEOUT)) {
        timeout = Timeout.ofMilliseconds((long) request.get(TIMEOUT));
    } else {
        timeout = null;
    }
    final ClassicTestClient client = new ClassicTestClient(SocketConfig.custom().setSoTimeout(timeout).build());
    // Append the path to the defaultURI.
    String tempDefaultURI = defaultURI;
    if (!defaultURI.endsWith("/")) {
        tempDefaultURI += "/";
    }
    final URI startingURI = new URI(tempDefaultURI + request.get(PATH));
    final URI uri;
    // append each parameter in the query to the uri.
    @SuppressWarnings("unchecked") final Map<String, String> queryMap = (Map<String, String>) request.get(QUERY);
    if (queryMap != null) {
        final String existingQuery = startingURI.getRawQuery();
        final StringBuilder newQuery = new StringBuilder(existingQuery == null ? "" : existingQuery);
        // append each parm to the query
        for (final Entry<String, String> parm : queryMap.entrySet()) {
            newQuery.append("&").append(parm.getKey()).append("=").append(parm.getValue());
        }
        // create a uri with the new query.
        uri = new URI(startingURI.getRawSchemeSpecificPart(), startingURI.getRawUserInfo(), startingURI.getHost(), startingURI.getPort(), startingURI.getRawPath(), newQuery.toString(), startingURI.getRawFragment());
    } else {
        uri = startingURI;
    }
    final BasicClassicHttpRequest httpRequest = new BasicClassicHttpRequest(request.get(METHOD).toString(), uri);
    if (request.containsKey(PROTOCOL_VERSION)) {
        httpRequest.setVersion((ProtocolVersion) request.get(PROTOCOL_VERSION));
    }
    // call addHeader for each header in headers.
    @SuppressWarnings("unchecked") final Map<String, String> headersMap = (Map<String, String>) request.get(HEADERS);
    if (headersMap != null) {
        for (final Entry<String, String> header : headersMap.entrySet()) {
            httpRequest.addHeader(header.getKey(), header.getValue());
        }
    }
    // call setEntity if a body is specified.
    final String requestBody = (String) request.get(BODY);
    if (requestBody != null) {
        final String requestContentType = (String) request.get(CONTENT_TYPE);
        final StringEntity entity = requestContentType != null ? new StringEntity(requestBody, ContentType.parse(requestContentType)) : new StringEntity(requestBody);
        httpRequest.setEntity(entity);
    }
    client.start(null);
    // Now start the request.
    final HttpHost host = new HttpHost(uri.getHost(), uri.getPort());
    final HttpCoreContext context = HttpCoreContext.create();
    try (final ClassicHttpResponse response = client.execute(host, httpRequest, context)) {
        // Prepare the response.  It will contain status, body, headers, and contentType.
        final HttpEntity entity = response.getEntity();
        final String body = entity == null ? null : EntityUtils.toString(entity);
        final String contentType = entity == null ? null : entity.getContentType();
        // prepare the returned information
        final Map<String, Object> ret = new HashMap<>();
        ret.put(STATUS, response.getCode());
        // convert the headers to a Map
        final Map<String, Object> headerMap = new HashMap<>();
        for (final Header header : response.getHeaders()) {
            headerMap.put(header.getName(), header.getValue());
        }
        ret.put(HEADERS, headerMap);
        ret.put(BODY, body);
        ret.put(CONTENT_TYPE, contentType);
        return ret;
    }
}
Also used : ClassicHttpResponse(org.apache.hc.core5.http.ClassicHttpResponse) HttpEntity(org.apache.hc.core5.http.HttpEntity) HashMap(java.util.HashMap) Timeout(org.apache.hc.core5.util.Timeout) URI(java.net.URI) StringEntity(org.apache.hc.core5.http.io.entity.StringEntity) BasicClassicHttpRequest(org.apache.hc.core5.http.message.BasicClassicHttpRequest) Header(org.apache.hc.core5.http.Header) HttpHost(org.apache.hc.core5.http.HttpHost) ClassicTestClient(org.apache.hc.core5.testing.classic.ClassicTestClient) HttpCoreContext(org.apache.hc.core5.http.protocol.HttpCoreContext) HttpException(org.apache.hc.core5.http.HttpException) HashMap(java.util.HashMap) Map(java.util.Map)

Example 3 with ProtocolVersion

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

the class H2ResponseConnControl method process.

@Override
public void process(final HttpResponse response, final EntityDetails entity, final HttpContext context) throws HttpException, IOException {
    Args.notNull(context, "HTTP context");
    final ProtocolVersion ver = context.getProtocolVersion();
    if (ver.getMajor() < 2) {
        super.process(response, entity, context);
    }
}
Also used : ProtocolVersion(org.apache.hc.core5.http.ProtocolVersion)

Example 4 with ProtocolVersion

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

the class ClientHttp1StreamHandler method consumeHeader.

void consumeHeader(final HttpResponse response, final EntityDetails entityDetails) throws HttpException, IOException {
    if (done.get() || responseState != MessageState.HEADERS) {
        throw new ProtocolException("Unexpected message head");
    }
    final ProtocolVersion transportVersion = response.getVersion();
    if (transportVersion != null && transportVersion.greaterEquals(HttpVersion.HTTP_2)) {
        throw new UnsupportedHttpVersionException(transportVersion);
    }
    final int status = response.getCode();
    if (status < HttpStatus.SC_INFORMATIONAL) {
        throw new ProtocolException("Invalid response: " + new StatusLine(response));
    }
    if (status > HttpStatus.SC_CONTINUE && status < HttpStatus.SC_SUCCESS) {
        exchangeHandler.consumeInformation(response, context);
    } else {
        if (!connectionReuseStrategy.keepAlive(committedRequest, response, context)) {
            keepAlive = false;
        }
    }
    if (requestState == MessageState.ACK) {
        if (status == HttpStatus.SC_CONTINUE || status >= HttpStatus.SC_SUCCESS) {
            outputChannel.setSocketTimeout(timeout);
            requestState = MessageState.BODY;
            if (status < HttpStatus.SC_CLIENT_ERROR) {
                exchangeHandler.produce(internalDataChannel);
            }
        }
    }
    if (status < HttpStatus.SC_SUCCESS) {
        return;
    }
    if (requestState == MessageState.BODY) {
        if (status >= HttpStatus.SC_CLIENT_ERROR) {
            requestState = MessageState.COMPLETE;
            if (!outputChannel.abortGracefully()) {
                keepAlive = false;
            }
        }
    }
    context.setProtocolVersion(transportVersion != null ? transportVersion : HttpVersion.HTTP_1_1);
    context.setAttribute(HttpCoreContext.HTTP_RESPONSE, response);
    httpProcessor.process(response, entityDetails, context);
    if (entityDetails == null && !keepAlive) {
        outputChannel.close();
    }
    exchangeHandler.consumeResponse(response, entityDetails, context);
    if (entityDetails == null) {
        responseState = MessageState.COMPLETE;
    } else {
        responseState = MessageState.BODY;
    }
}
Also used : StatusLine(org.apache.hc.core5.http.message.StatusLine) ProtocolException(org.apache.hc.core5.http.ProtocolException) UnsupportedHttpVersionException(org.apache.hc.core5.http.UnsupportedHttpVersionException) ProtocolVersion(org.apache.hc.core5.http.ProtocolVersion)

Example 5 with ProtocolVersion

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

the class DefaultHttpRequestWriter method writeHeadLine.

@Override
protected void writeHeadLine(final T message, final CharArrayBuffer lineBuf) throws IOException {
    lineBuf.clear();
    final ProtocolVersion transportVersion = message.getVersion();
    getLineFormatter().formatRequestLine(lineBuf, new RequestLine(message.getMethod(), message.getRequestUri(), transportVersion != null ? transportVersion : HttpVersion.HTTP_1_1));
}
Also used : RequestLine(org.apache.hc.core5.http.message.RequestLine) ProtocolVersion(org.apache.hc.core5.http.ProtocolVersion)

Aggregations

ProtocolVersion (org.apache.hc.core5.http.ProtocolVersion)35 ProtocolException (org.apache.hc.core5.http.ProtocolException)8 UnsupportedHttpVersionException (org.apache.hc.core5.http.UnsupportedHttpVersionException)8 Header (org.apache.hc.core5.http.Header)6 HttpException (org.apache.hc.core5.http.HttpException)6 ClassicHttpResponse (org.apache.hc.core5.http.ClassicHttpResponse)4 ParseException (org.apache.hc.core5.http.ParseException)4 IOException (java.io.IOException)3 HashMap (java.util.HashMap)3 Map (java.util.Map)3 ClassicHttpRequest (org.apache.hc.core5.http.ClassicHttpRequest)3 HttpHost (org.apache.hc.core5.http.HttpHost)3 HttpResponse (org.apache.hc.core5.http.HttpResponse)3 StringEntity (org.apache.hc.core5.http.io.entity.StringEntity)3 StatusLine (org.apache.hc.core5.http.message.StatusLine)3 Test (org.junit.jupiter.api.Test)3 URI (java.net.URI)2 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)2 AtomicReference (java.util.concurrent.atomic.AtomicReference)2 SSLSession (javax.net.ssl.SSLSession)2