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