Search in sources :

Example 26 with Method

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

the class AsyncRequestBuilder method build.

@Override
public AsyncRequestProducer build() {
    String path = getPath();
    if (TextUtils.isEmpty(path)) {
        path = "/";
    }
    AsyncEntityProducer entityProducerCopy = entityProducer;
    final String method = getMethod();
    final List<NameValuePair> parameters = getParameters();
    if (parameters != null && !parameters.isEmpty()) {
        final Charset charset = getCharset();
        if (entityProducerCopy == null && (Method.POST.isSame(method) || Method.PUT.isSame(method))) {
            final String content = WWWFormCodec.format(parameters, charset != null ? charset : ContentType.APPLICATION_FORM_URLENCODED.getCharset());
            entityProducerCopy = new StringAsyncEntityProducer(content, ContentType.APPLICATION_FORM_URLENCODED);
        } else {
            try {
                final URI uri = new URIBuilder(path).setCharset(charset).addParameters(parameters).build();
                path = uri.toASCIIString();
            } catch (final URISyntaxException ex) {
            // should never happen
            }
        }
    }
    if (entityProducerCopy != null && Method.TRACE.isSame(method)) {
        throw new IllegalStateException(Method.TRACE + " requests may not include an entity");
    }
    final BasicHttpRequest request = new BasicHttpRequest(method, getScheme(), getAuthority(), path);
    request.setVersion(getVersion());
    request.setHeaders(getHeaders());
    request.setAbsoluteRequestUri(isAbsoluteRequestUri());
    return new BasicRequestProducer(request, entityProducerCopy);
}
Also used : NameValuePair(org.apache.hc.core5.http.NameValuePair) StringAsyncEntityProducer(org.apache.hc.core5.http.nio.entity.StringAsyncEntityProducer) BasicAsyncEntityProducer(org.apache.hc.core5.http.nio.entity.BasicAsyncEntityProducer) AsyncEntityProducer(org.apache.hc.core5.http.nio.AsyncEntityProducer) StringAsyncEntityProducer(org.apache.hc.core5.http.nio.entity.StringAsyncEntityProducer) Charset(java.nio.charset.Charset) URISyntaxException(java.net.URISyntaxException) URI(java.net.URI) BasicHttpRequest(org.apache.hc.core5.http.message.BasicHttpRequest) URIBuilder(org.apache.hc.core5.net.URIBuilder)

Example 27 with Method

use of org.apache.hc.core5.http.Method in project ksql by confluentinc.

the class WebClient method send.

/**
 * Sends a POST request to a web server
 * This method requires a pre-configured http client instance
 *
 * @param customerId customer Id on behalf of which the request is sent
 * @param bytes request payload
 * @param httpPost A POST request structure
 * @param proxy a http (passive) proxy
 * @param httpClient http client instance configured by caller
 * @return an HTTP Status code
 * @see #send(String, byte[], HttpPost, ResponseHandler)
 */
@SuppressWarnings({ "checkstyle:CyclomaticComplexity", "checkstyle:FinalParameters" })
protected static int send(final String customerId, final byte[] bytes, final HttpPost httpPost, final HttpHost proxy, CloseableHttpClient httpClient, final ResponseHandler responseHandler) {
    int statusCode = DEFAULT_STATUS_CODE;
    if (bytes != null && bytes.length > 0 && httpPost != null && customerId != null) {
        // add the body to the request
        final MultipartEntityBuilder builder = MultipartEntityBuilder.create();
        builder.setMode(HttpMultipartMode.LEGACY);
        builder.addTextBody("cid", customerId);
        builder.addBinaryBody("file", bytes, ContentType.DEFAULT_BINARY, "filename");
        httpPost.setEntity(builder.build());
        httpPost.addHeader("api-version", "phone-home-v1");
        // set the HTTP config
        RequestConfig config = RequestConfig.custom().setConnectTimeout(Timeout.ofMilliseconds(REQUEST_TIMEOUT_MS)).setConnectionRequestTimeout(Timeout.ofMilliseconds(REQUEST_TIMEOUT_MS)).setResponseTimeout(Timeout.ofMilliseconds(REQUEST_TIMEOUT_MS)).build();
        CloseableHttpResponse response = null;
        try {
            if (proxy != null) {
                log.debug("setting proxy to {}", proxy);
                config = RequestConfig.copy(config).setProxy(proxy).build();
                httpPost.setConfig(config);
                final DefaultProxyRoutePlanner routePlanner = new DefaultProxyRoutePlanner(proxy);
                if (httpClient == null) {
                    httpClient = HttpClientBuilder.create().setRoutePlanner(routePlanner).setDefaultRequestConfig(config).build();
                }
            } else {
                if (httpClient == null) {
                    httpClient = HttpClientBuilder.create().setDefaultRequestConfig(config).build();
                }
            }
            response = httpClient.execute(httpPost);
            if (responseHandler != null) {
                responseHandler.handle(response);
            }
            // send request
            log.debug("POST request returned {}", new StatusLine(response).toString());
            statusCode = response.getCode();
        } catch (IOException e) {
            log.error("Could not submit metrics to Confluent: {}", e.getMessage());
        } finally {
            if (httpClient != null) {
                try {
                    httpClient.close();
                } catch (IOException e) {
                    log.warn("could not close http client", e);
                }
            }
            if (response != null) {
                try {
                    response.close();
                } catch (IOException e) {
                    log.warn("could not close http response", e);
                }
            }
        }
    } else {
        statusCode = HttpStatus.SC_BAD_REQUEST;
    }
    return statusCode;
}
Also used : StatusLine(org.apache.hc.core5.http.message.StatusLine) RequestConfig(org.apache.hc.client5.http.config.RequestConfig) MultipartEntityBuilder(org.apache.hc.client5.http.entity.mime.MultipartEntityBuilder) CloseableHttpResponse(org.apache.hc.client5.http.impl.classic.CloseableHttpResponse) DefaultProxyRoutePlanner(org.apache.hc.client5.http.impl.routing.DefaultProxyRoutePlanner) IOException(java.io.IOException)

Example 28 with Method

use of org.apache.hc.core5.http.Method 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 29 with Method

use of org.apache.hc.core5.http.Method in project wiremock by wiremock.

the class WebhooksAcceptanceTest method addsRandomDelayViaJSON.

@Test
public void addsRandomDelayViaJSON() throws Exception {
    client.postJson("/__admin/mappings", "{\n" + "  \"request\" : {\n" + "    \"urlPath\" : \"/delayed\",\n" + "    \"method\" : \"POST\"\n" + "  },\n" + "  \"postServeActions\" : [{\n" + "    \"name\" : \"webhook\",\n" + "    \"parameters\" : {\n" + "      \"method\" : \"GET\",\n" + "      \"url\" : \"" + targetServer.baseUrl() + "/callback\",\n" + "      \"delay\" : {\n" + "        \"type\" : \"uniform\",\n" + "        \"lower\": 500,\n" + "        \"upper\": 1000\n" + "      }\n" + "    }\n" + "  }]\n" + "}");
    verify(0, postRequestedFor(anyUrl()));
    client.post("/delayed", new StringEntity("", TEXT_PLAIN));
    Stopwatch stopwatch = Stopwatch.createStarted();
    waitForRequestToTargetServer();
    stopwatch.stop();
    long elapsedMilliseconds = stopwatch.elapsed(MILLISECONDS);
    assertThat(elapsedMilliseconds, greaterThanOrEqualTo(500L));
    assertThat(elapsedMilliseconds, lessThanOrEqualTo(1500L));
    verify(1, getRequestedFor(urlEqualTo("/callback")));
}
Also used : StringEntity(org.apache.hc.core5.http.io.entity.StringEntity) Stopwatch(com.google.common.base.Stopwatch) Test(org.junit.jupiter.api.Test)

Example 30 with Method

use of org.apache.hc.core5.http.Method in project wiremock by wiremock.

the class AdminRequestHandlerTest method shouldLogInfoOnRequest.

@Test
public void shouldLogInfoOnRequest() throws UnsupportedEncodingException {
    WireMockTestClient client = new WireMockTestClient(wm.getPort());
    String postHeaderABCName = "ABC";
    String postHeaderABCValue = "abc123";
    String postBody = "{\n" + "    \"request\": {\n" + "        \"method\": \"GET\",\n" + "        \"url\": \"/some/thing\"\n" + "    },\n" + "    \"response\": {\n" + "        \"status\": 200,\n" + "        \"body\": \"Hello world!\",\n" + "        \"headers\": {\n" + "            \"Content-Type\": \"text/plain\"\n" + "        }\n" + "    }\n" + "}";
    client.post("/__admin/mappings", new StringEntity(postBody), withHeader(postHeaderABCName, postHeaderABCValue));
    verify(notifier).info(contains("Admin request received:\n127.0.0.1 - POST /mappings\n"));
    verify(notifier).info(contains(postHeaderABCName + ": [" + postHeaderABCValue + "]\n"));
    verify(notifier).info(contains(postBody));
}
Also used : StringEntity(org.apache.hc.core5.http.io.entity.StringEntity) WireMockTestClient(com.github.tomakehurst.wiremock.testsupport.WireMockTestClient) Test(org.junit.jupiter.api.Test)

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