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);
}
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;
}
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);
}
}
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")));
}
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));
}
Aggregations