Search in sources :

Example 1 with InputStreamEntity

use of org.apache.hc.core5.http.io.entity.InputStreamEntity in project httpcomponents-core by apache.

the class TestHttpService method testExecutionEntityEnclosingRequest.

@Test
public void testExecutionEntityEnclosingRequest() throws Exception {
    final HttpCoreContext context = HttpCoreContext.create();
    final ClassicHttpRequest request = new BasicClassicHttpRequest(Method.POST, "/");
    final InputStream inStream = Mockito.mock(InputStream.class);
    final InputStreamEntity entity = new InputStreamEntity(inStream, -1, null);
    request.setEntity(entity);
    Mockito.when(conn.receiveRequestHeader()).thenReturn(request);
    Mockito.when(responseFactory.newHttpResponse(200)).thenReturn(response);
    Mockito.when(connReuseStrategy.keepAlive(ArgumentMatchers.eq(request), ArgumentMatchers.argThat(errorResponse -> errorResponse.getCode() == HttpStatus.SC_NOT_IMPLEMENTED), ArgumentMatchers.eq(context))).thenReturn(Boolean.TRUE);
    httpservice.handleRequest(conn, context);
    final ArgumentCaptor<ClassicHttpResponse> responseCaptor = ArgumentCaptor.forClass(ClassicHttpResponse.class);
    Mockito.verify(conn).sendResponseHeader(responseCaptor.capture());
    final ClassicHttpResponse response = responseCaptor.getValue();
    Assertions.assertNotNull(response);
    Assertions.assertEquals(HttpStatus.SC_NOT_IMPLEMENTED, response.getCode());
    Assertions.assertSame(request, context.getRequest());
    Mockito.verify(httprocessor).process(request, request.getEntity(), context);
    Mockito.verify(inStream).close();
    Mockito.verify(httprocessor).process(response, response.getEntity(), context);
    Mockito.verify(conn).sendResponseHeader(response);
    Mockito.verify(conn).sendResponseEntity(response);
    Mockito.verify(conn).flush();
    Mockito.verify(conn, Mockito.never()).close();
    Mockito.verify(response).close();
}
Also used : HttpCoreContext(org.apache.hc.core5.http.protocol.HttpCoreContext) BeforeEach(org.junit.jupiter.api.BeforeEach) MethodNotSupportedException(org.apache.hc.core5.http.MethodNotSupportedException) ArgumentMatchers(org.mockito.ArgumentMatchers) Mock(org.mockito.Mock) UnsupportedHttpVersionException(org.apache.hc.core5.http.UnsupportedHttpVersionException) HttpResponseFactory(org.apache.hc.core5.http.HttpResponseFactory) InputStreamEntity(org.apache.hc.core5.http.io.entity.InputStreamEntity) HttpRequestMapper(org.apache.hc.core5.http.HttpRequestMapper) HttpProcessor(org.apache.hc.core5.http.protocol.HttpProcessor) MockitoAnnotations(org.mockito.MockitoAnnotations) ArgumentCaptor(org.mockito.ArgumentCaptor) ClassicHttpResponse(org.apache.hc.core5.http.ClassicHttpResponse) Spy(org.mockito.Spy) HttpServerConnection(org.apache.hc.core5.http.io.HttpServerConnection) ProtocolException(org.apache.hc.core5.http.ProtocolException) ConnectionReuseStrategy(org.apache.hc.core5.http.ConnectionReuseStrategy) BasicClassicHttpResponse(org.apache.hc.core5.http.message.BasicClassicHttpResponse) BasicClassicHttpRequest(org.apache.hc.core5.http.message.BasicClassicHttpRequest) ClassicHttpRequest(org.apache.hc.core5.http.ClassicHttpRequest) Test(org.junit.jupiter.api.Test) HttpHeaders(org.apache.hc.core5.http.HttpHeaders) Mockito(org.mockito.Mockito) List(java.util.List) HttpRequestHandler(org.apache.hc.core5.http.io.HttpRequestHandler) HeaderElements(org.apache.hc.core5.http.HeaderElements) Method(org.apache.hc.core5.http.Method) Assertions(org.junit.jupiter.api.Assertions) HttpStatus(org.apache.hc.core5.http.HttpStatus) InputStream(java.io.InputStream) ClassicHttpResponse(org.apache.hc.core5.http.ClassicHttpResponse) BasicClassicHttpResponse(org.apache.hc.core5.http.message.BasicClassicHttpResponse) BasicClassicHttpRequest(org.apache.hc.core5.http.message.BasicClassicHttpRequest) ClassicHttpRequest(org.apache.hc.core5.http.ClassicHttpRequest) BasicClassicHttpRequest(org.apache.hc.core5.http.message.BasicClassicHttpRequest) InputStream(java.io.InputStream) HttpCoreContext(org.apache.hc.core5.http.protocol.HttpCoreContext) InputStreamEntity(org.apache.hc.core5.http.io.entity.InputStreamEntity) Test(org.junit.jupiter.api.Test)

Example 2 with InputStreamEntity

use of org.apache.hc.core5.http.io.entity.InputStreamEntity in project geo-platform by geosdi.

the class GeoSDIHttpClient5 method post.

/**
 * Executes an HTTP POST request against the provided URL, sending the contents of {@code
 * postContent} as the POST method body and setting the Content-Type request header to {@code
 * postContentType} if given, and returns the server response.
 *
 * <p>If an HTTP authentication {@link #getUser() user} and {@link #getPassword() password} is
 * set, the appropriate authentication HTTP header will be sent with the request.
 *
 * <p>If a {@link #getConnectTimeout() connection timeout} is set, the http connection will be
 * set to respect that timeout.
 *
 * <p>If a {@link #getReadTimeout() read timeout} is set, the http connection will be set to
 * respect it.
 *
 * @param url the URL against which to execute the POST request
 * @param postContent an input stream with the contents of the POST body
 * @param postContentType the MIME type of the contents sent as the request POST body, can be
 * {@code null}
 * @return the {@link HTTPResponse} encapsulating the response to the HTTP POST request
 */
@Override
public HTTPResponse post(URL url, InputStream postContent, String postContentType) throws IOException {
    HttpPost httpPost = new HttpPost(url.toExternalForm());
    logger.info("Inject OpenAM Cookie");
    if ((this.headers != null) && !(this.headers.isEmpty())) {
        List<String> values = this.headers.stream().map(value -> String.join("=", value.getHeaderKey(), value.getHeaderValue())).collect(toList());
        httpPost.setHeader("Cookie", String.join(";", values));
    }
    HttpEntity requestEntity = new InputStreamEntity(postContent, ContentType.create(postContentType));
    httpPost.setEntity(requestEntity);
    CloseableHttpResponse response = null;
    if (((this.user != null) && !(this.user.trim().isEmpty())) && ((this.password != null) && !(this.password.trim().isEmpty()))) {
        try {
            URI uri = url.toURI();
            HttpClientContext localContext = create();
            HttpHost targetHost = new HttpHost(uri.getScheme(), uri.getHost(), this.retrieveNoSetPort(uri));
            BasicScheme basicAuth = new BasicScheme();
            basicAuth.initPreemptive(new UsernamePasswordCredentials(this.user, this.password.toCharArray()));
            localContext.resetAuthExchange(targetHost, basicAuth);
            response = this.httpClient.execute(targetHost, httpPost, localContext);
        } catch (URISyntaxException ex) {
            throw new IOException("URISyntaxException error : " + ex.getMessage() + " for URL " + url.toExternalForm());
        }
    } else {
        response = this.httpClient.execute(httpPost);
    }
    int responseCode = response.getCode();
    if (200 != responseCode) {
        response.close();
        throw new IOException("Server returned HTTP error code " + responseCode + " for URL " + url.toExternalForm());
    } else {
        return new GeoSDIHttpClient5.HttpMethodResponse(response);
    }
}
Also used : GZIPInputStream(java.util.zip.GZIPInputStream) URL(java.net.URL) URISyntaxException(java.net.URISyntaxException) LoggerFactory(org.slf4j.LoggerFactory) ConnectionSocketFactory(org.apache.hc.client5.http.socket.ConnectionSocketFactory) BasicCredentialsProvider(org.apache.hc.client5.http.impl.auth.BasicCredentialsProvider) URI(java.net.URI) TimeValue(org.apache.hc.core5.util.TimeValue) HttpRequestExecutor(org.apache.hc.core5.http.impl.io.HttpRequestExecutor) RegistryBuilder(org.apache.hc.core5.http.config.RegistryBuilder) HTTPClient(org.geotools.http.HTTPClient) List(java.util.List) HttpEntity(org.apache.hc.core5.http.HttpEntity) UnsupportedCharsetException(java.nio.charset.UnsupportedCharsetException) DefaultConnectionReuseStrategy(org.apache.hc.core5.http.impl.DefaultConnectionReuseStrategy) TRUE(java.lang.Boolean.TRUE) Timeout.of(org.apache.hc.core5.util.Timeout.of) HttpClientContext(org.apache.hc.client5.http.protocol.HttpClientContext) BasicScheme(org.apache.hc.client5.http.impl.auth.BasicScheme) MINUTES(java.util.concurrent.TimeUnit.MINUTES) HttpGet(org.apache.hc.client5.http.classic.methods.HttpGet) HttpClientConnectionManager(org.apache.hc.client5.http.io.HttpClientConnectionManager) InputStreamEntity(org.apache.hc.core5.http.io.entity.InputStreamEntity) Lists(com.google.common.collect.Lists) Charset(java.nio.charset.Charset) HTTPResponse(org.geotools.http.HTTPResponse) CloseableHttpResponse(org.apache.hc.client5.http.impl.classic.CloseableHttpResponse) RequestConfig(org.apache.hc.client5.http.config.RequestConfig) HttpClients(org.apache.hc.client5.http.impl.classic.HttpClients) Logger(org.slf4j.Logger) UsernamePasswordCredentials(org.apache.hc.client5.http.auth.UsernamePasswordCredentials) WMSHeaderParam(org.geosdi.geoplatform.services.request.WMSHeaderParam) UTF_8(java.nio.charset.StandardCharsets.UTF_8) Header(org.apache.hc.core5.http.Header) NoopHostnameVerifier(org.apache.hc.client5.http.ssl.NoopHostnameVerifier) IOException(java.io.IOException) PoolingHttpClientConnectionManager(org.apache.hc.client5.http.impl.io.PoolingHttpClientConnectionManager) HttpPost(org.apache.hc.client5.http.classic.methods.HttpPost) SSLConnectionSocketFactory(org.apache.hc.client5.http.ssl.SSLConnectionSocketFactory) TimeUnit(java.util.concurrent.TimeUnit) SSLContextBuilder(org.apache.hc.core5.ssl.SSLContextBuilder) Collectors.toList(java.util.stream.Collectors.toList) HttpHost(org.apache.hc.core5.http.HttpHost) ContentType(org.apache.hc.core5.http.ContentType) PlainConnectionSocketFactory(org.apache.hc.client5.http.socket.PlainConnectionSocketFactory) Long.valueOf(java.lang.Long.valueOf) HttpClientContext.create(org.apache.hc.client5.http.protocol.HttpClientContext.create) CloseableHttpClient(org.apache.hc.client5.http.impl.classic.CloseableHttpClient) SECONDS(java.util.concurrent.TimeUnit.SECONDS) InputStream(java.io.InputStream) HttpPost(org.apache.hc.client5.http.classic.methods.HttpPost) BasicScheme(org.apache.hc.client5.http.impl.auth.BasicScheme) HttpEntity(org.apache.hc.core5.http.HttpEntity) HttpClientContext(org.apache.hc.client5.http.protocol.HttpClientContext) URISyntaxException(java.net.URISyntaxException) IOException(java.io.IOException) URI(java.net.URI) InputStreamEntity(org.apache.hc.core5.http.io.entity.InputStreamEntity) UsernamePasswordCredentials(org.apache.hc.client5.http.auth.UsernamePasswordCredentials) HttpHost(org.apache.hc.core5.http.HttpHost) CloseableHttpResponse(org.apache.hc.client5.http.impl.classic.CloseableHttpResponse)

Example 3 with InputStreamEntity

use of org.apache.hc.core5.http.io.entity.InputStreamEntity in project wiremock by wiremock.

the class ProxyResponseRenderer method buildEntityFrom.

private static HttpEntity buildEntityFrom(Request originalRequest) {
    ContentTypeHeader contentTypeHeader = originalRequest.contentTypeHeader().or("text/plain");
    ContentType contentType = ContentType.create(contentTypeHeader.mimeTypePart(), contentTypeHeader.encodingPart().or("utf-8"));
    if (originalRequest.containsHeader(TRANSFER_ENCODING) && originalRequest.header(TRANSFER_ENCODING).firstValue().equals("chunked")) {
        return applyGzipWrapperIfRequired(originalRequest, new InputStreamEntity(new ByteArrayInputStream(originalRequest.getBody()), -1, contentType));
    }
    return applyGzipWrapperIfRequired(originalRequest, new ByteArrayEntity(originalRequest.getBody(), ContentType.DEFAULT_BINARY));
}
Also used : ByteArrayEntity(org.apache.hc.core5.http.io.entity.ByteArrayEntity) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStreamEntity(org.apache.hc.core5.http.io.entity.InputStreamEntity)

Example 4 with InputStreamEntity

use of org.apache.hc.core5.http.io.entity.InputStreamEntity in project httpcomponents-core by apache.

the class TestHttpService method testExecutionEntityEnclosingRequestWithExpectContinue.

@Test
public void testExecutionEntityEnclosingRequestWithExpectContinue() throws Exception {
    final HttpCoreContext context = HttpCoreContext.create();
    final ClassicHttpRequest request = new BasicClassicHttpRequest(Method.POST, "/");
    request.addHeader(HttpHeaders.EXPECT, HeaderElements.CONTINUE);
    final InputStream inStream = Mockito.mock(InputStream.class);
    final InputStreamEntity entity = new InputStreamEntity(inStream, -1, null);
    request.setEntity(entity);
    Mockito.when(conn.receiveRequestHeader()).thenReturn(request);
    Mockito.when(responseFactory.newHttpResponse(200)).thenReturn(response);
    Mockito.when(connReuseStrategy.keepAlive(ArgumentMatchers.eq(request), ArgumentMatchers.argThat(errorResponse -> errorResponse.getCode() == HttpStatus.SC_NOT_IMPLEMENTED), ArgumentMatchers.eq(context))).thenReturn(Boolean.TRUE);
    httpservice.handleRequest(conn, context);
    final ArgumentCaptor<ClassicHttpResponse> responseCaptor = ArgumentCaptor.forClass(ClassicHttpResponse.class);
    Mockito.verify(conn, Mockito.times(2)).sendResponseHeader(responseCaptor.capture());
    final List<ClassicHttpResponse> responses = responseCaptor.getAllValues();
    Assertions.assertNotNull(responses);
    Assertions.assertEquals(2, responses.size());
    final ClassicHttpResponse ack = responses.get(0);
    final ClassicHttpResponse response = responses.get(1);
    Assertions.assertEquals(HttpStatus.SC_CONTINUE, ack.getCode());
    Assertions.assertEquals(HttpStatus.SC_NOT_IMPLEMENTED, response.getCode());
    Assertions.assertSame(request, context.getRequest());
    Mockito.verify(httprocessor).process(request, request.getEntity(), context);
    Mockito.verify(inStream).close();
    Mockito.verify(httprocessor).process(response, response.getEntity(), context);
    Mockito.verify(conn).sendResponseHeader(response);
    Mockito.verify(conn).sendResponseEntity(response);
    Mockito.verify(conn, Mockito.times(2)).flush();
    Mockito.verify(conn, Mockito.never()).close();
    Mockito.verify(response).close();
}
Also used : HttpCoreContext(org.apache.hc.core5.http.protocol.HttpCoreContext) BeforeEach(org.junit.jupiter.api.BeforeEach) MethodNotSupportedException(org.apache.hc.core5.http.MethodNotSupportedException) ArgumentMatchers(org.mockito.ArgumentMatchers) Mock(org.mockito.Mock) UnsupportedHttpVersionException(org.apache.hc.core5.http.UnsupportedHttpVersionException) HttpResponseFactory(org.apache.hc.core5.http.HttpResponseFactory) InputStreamEntity(org.apache.hc.core5.http.io.entity.InputStreamEntity) HttpRequestMapper(org.apache.hc.core5.http.HttpRequestMapper) HttpProcessor(org.apache.hc.core5.http.protocol.HttpProcessor) MockitoAnnotations(org.mockito.MockitoAnnotations) ArgumentCaptor(org.mockito.ArgumentCaptor) ClassicHttpResponse(org.apache.hc.core5.http.ClassicHttpResponse) Spy(org.mockito.Spy) HttpServerConnection(org.apache.hc.core5.http.io.HttpServerConnection) ProtocolException(org.apache.hc.core5.http.ProtocolException) ConnectionReuseStrategy(org.apache.hc.core5.http.ConnectionReuseStrategy) BasicClassicHttpResponse(org.apache.hc.core5.http.message.BasicClassicHttpResponse) BasicClassicHttpRequest(org.apache.hc.core5.http.message.BasicClassicHttpRequest) ClassicHttpRequest(org.apache.hc.core5.http.ClassicHttpRequest) Test(org.junit.jupiter.api.Test) HttpHeaders(org.apache.hc.core5.http.HttpHeaders) Mockito(org.mockito.Mockito) List(java.util.List) HttpRequestHandler(org.apache.hc.core5.http.io.HttpRequestHandler) HeaderElements(org.apache.hc.core5.http.HeaderElements) Method(org.apache.hc.core5.http.Method) Assertions(org.junit.jupiter.api.Assertions) HttpStatus(org.apache.hc.core5.http.HttpStatus) InputStream(java.io.InputStream) ClassicHttpResponse(org.apache.hc.core5.http.ClassicHttpResponse) BasicClassicHttpResponse(org.apache.hc.core5.http.message.BasicClassicHttpResponse) BasicClassicHttpRequest(org.apache.hc.core5.http.message.BasicClassicHttpRequest) ClassicHttpRequest(org.apache.hc.core5.http.ClassicHttpRequest) BasicClassicHttpRequest(org.apache.hc.core5.http.message.BasicClassicHttpRequest) InputStream(java.io.InputStream) HttpCoreContext(org.apache.hc.core5.http.protocol.HttpCoreContext) InputStreamEntity(org.apache.hc.core5.http.io.entity.InputStreamEntity) Test(org.junit.jupiter.api.Test)

Example 5 with InputStreamEntity

use of org.apache.hc.core5.http.io.entity.InputStreamEntity in project mercury by yellow013.

the class ClientChunkEncodedPost method main.

public static void main(final String[] args) throws Exception {
    if (args.length != 1) {
        System.out.println("File path not given");
        System.exit(1);
    }
    try (final CloseableHttpClient httpclient = HttpClients.createDefault()) {
        final HttpPost httppost = new HttpPost("http://httpbin.org/post");
        final File file = new File(args[0]);
        final InputStreamEntity reqEntity = new InputStreamEntity(new FileInputStream(file), -1, ContentType.APPLICATION_OCTET_STREAM);
        // It may be more appropriate to use FileEntity class in this particular
        // instance but we are using a more generic InputStreamEntity to demonstrate
        // the capability to stream out data from any arbitrary source
        // 
        // FileEntity entity = new FileEntity(file, "binary/octet-stream");
        httppost.setEntity(reqEntity);
        System.out.println("Executing request " + httppost.getMethod() + " " + httppost.getUri());
        try (final CloseableHttpResponse response = httpclient.execute(httppost)) {
            System.out.println("----------------------------------------");
            System.out.println(response.getCode() + " " + response.getReasonPhrase());
            System.out.println(EntityUtils.toString(response.getEntity()));
        }
    }
}
Also used : CloseableHttpClient(org.apache.hc.client5.http.impl.classic.CloseableHttpClient) HttpPost(org.apache.hc.client5.http.classic.methods.HttpPost) CloseableHttpResponse(org.apache.hc.client5.http.impl.classic.CloseableHttpResponse) File(java.io.File) FileInputStream(java.io.FileInputStream) InputStreamEntity(org.apache.hc.core5.http.io.entity.InputStreamEntity)

Aggregations

InputStreamEntity (org.apache.hc.core5.http.io.entity.InputStreamEntity)5 InputStream (java.io.InputStream)3 List (java.util.List)3 HttpPost (org.apache.hc.client5.http.classic.methods.HttpPost)2 CloseableHttpClient (org.apache.hc.client5.http.impl.classic.CloseableHttpClient)2 CloseableHttpResponse (org.apache.hc.client5.http.impl.classic.CloseableHttpResponse)2 ClassicHttpRequest (org.apache.hc.core5.http.ClassicHttpRequest)2 ClassicHttpResponse (org.apache.hc.core5.http.ClassicHttpResponse)2 ConnectionReuseStrategy (org.apache.hc.core5.http.ConnectionReuseStrategy)2 Lists (com.google.common.collect.Lists)1 ByteArrayInputStream (java.io.ByteArrayInputStream)1 File (java.io.File)1 FileInputStream (java.io.FileInputStream)1 IOException (java.io.IOException)1 TRUE (java.lang.Boolean.TRUE)1 Long.valueOf (java.lang.Long.valueOf)1 URI (java.net.URI)1 URISyntaxException (java.net.URISyntaxException)1 URL (java.net.URL)1 Charset (java.nio.charset.Charset)1