use of org.apache.hc.core5.http.Method in project httpcomponents-core by apache.
the class TestDefaultH2RequestConverter method testConvertFromFieldsConnectPresentPath.
@Test
public void testConvertFromFieldsConnectPresentPath() throws Exception {
final List<Header> headers = Arrays.asList(new BasicHeader(":method", "CONNECT"), new BasicHeader(":authority", "www.example.com"), new BasicHeader(":path", "/"), new BasicHeader("custom", "value"));
final DefaultH2RequestConverter converter = new DefaultH2RequestConverter();
Assertions.assertThrows(HttpException.class, () -> converter.convert(headers), "Header ':path' must not be set for CONNECT request");
}
use of org.apache.hc.core5.http.Method in project httpcomponents-core by apache.
the class TestDefaultH2RequestConverter method testConvertFromMessageConnect.
@Test
public void testConvertFromMessageConnect() throws Exception {
final HttpRequest request = new BasicHttpRequest("CONNECT", new HttpHost("host:80"), null);
request.addHeader("custom123", "Value");
final DefaultH2RequestConverter converter = new DefaultH2RequestConverter();
final List<Header> headers = converter.convert(request);
Assertions.assertNotNull(headers);
Assertions.assertEquals(3, headers.size());
final Header header1 = headers.get(0);
Assertions.assertEquals(":method", header1.getName());
Assertions.assertEquals("CONNECT", header1.getValue());
final Header header2 = headers.get(1);
Assertions.assertEquals(":authority", header2.getName());
Assertions.assertEquals("host:80", header2.getValue());
final Header header3 = headers.get(2);
Assertions.assertEquals("custom123", header3.getName());
Assertions.assertEquals("Value", header3.getValue());
}
use of org.apache.hc.core5.http.Method in project httpcomponents-core by apache.
the class ReactiveRandomProcessor method processRequest.
@Override
public void processRequest(final HttpRequest request, final EntityDetails entityDetails, final ResponseChannel responseChannel, final HttpContext context, final Publisher<ByteBuffer> requestBody, final Callback<Publisher<ByteBuffer>> responseBodyCallback) throws HttpException, IOException {
final String method = request.getMethod();
if (!"GET".equalsIgnoreCase(method) && !"HEAD".equalsIgnoreCase(method) && !"POST".equalsIgnoreCase(method) && !"PUT".equalsIgnoreCase(method)) {
throw new MethodNotSupportedException(method + " not supported by " + getClass().getName());
}
final URI uri;
try {
uri = request.getUri();
} catch (final URISyntaxException ex) {
throw new ProtocolException(ex.getMessage(), ex);
}
final String path = uri.getPath();
final int slash = path.lastIndexOf('/');
if (slash != -1) {
final String payload = path.substring(slash + 1);
final long n;
if (!payload.isEmpty()) {
try {
n = Long.parseLong(payload);
} catch (final NumberFormatException ex) {
throw new ProtocolException("Invalid request path: " + path);
}
} else {
// random length, but make sure at least something is sent
n = 1 + (int) (Math.random() * 79.0);
}
if (new BasicHeader(HttpHeaders.EXPECT, HeaderElements.CONTINUE).equals(request.getHeader(HttpHeaders.EXPECT))) {
responseChannel.sendInformation(new BasicHttpResponse(100), context);
}
final HttpResponse response = new BasicHttpResponse(HttpStatus.SC_OK);
final Flowable<ByteBuffer> stream = ReactiveTestUtils.produceStream(n);
final String hash = ReactiveTestUtils.getStreamHash(n);
response.addHeader("response-hash-code", hash);
final BasicEntityDetails basicEntityDetails = new BasicEntityDetails(n, ContentType.APPLICATION_OCTET_STREAM);
responseChannel.sendResponse(response, basicEntityDetails, context);
responseBodyCallback.execute(stream);
} else {
throw new ProtocolException("Invalid request path: " + path);
}
}
use of org.apache.hc.core5.http.Method in project httpcomponents-core by apache.
the class TestClassicTestClientTestingAdapter method withLiveServerEcho.
@Test
public void withLiveServerEcho() throws Exception {
final ClientTestingAdapter adapter = new ClassicTestClientTestingAdapter();
// Initialize the server-side request handler
server.registerHandler("/echo/*", new EchoHandler());
this.server.start();
final HttpHost target = new HttpHost("localhost", this.server.getPort());
final String defaultURI = target.toString();
final Map<String, Object> request = new HashMap<>();
request.put(PATH, ECHO_PATH);
request.put(METHOD, Method.POST.name());
final String body = "mybody";
request.put(BODY, body);
final Map<String, Object> responseExpectations = new HashMap<>();
final TestingFrameworkRequestHandler requestHandler = Mockito.mock(TestingFrameworkRequestHandler.class);
final Map<String, Object> response = adapter.execute(defaultURI, request, requestHandler, responseExpectations);
Assertions.assertNotNull(response, "response should not be null");
Assertions.assertEquals(200, response.get(STATUS), "status unexpected");
@SuppressWarnings("unchecked") final Map<String, Object> headers = (Map<String, Object>) response.get(HEADERS);
Assertions.assertNotNull(headers, "headers should be in the response");
Assertions.assertFalse(headers.isEmpty());
final String returnedBody = (String) response.get(BODY);
Assertions.assertNotNull(returnedBody, "body should be in the response");
Assertions.assertEquals(body, returnedBody, "Body should be echoed");
}
use of org.apache.hc.core5.http.Method 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;
}
}
Aggregations