Search in sources :

Example 6 with HttpMethod

use of io.vertx.core.http.HttpMethod in project vert.x by eclipse.

the class HttpTest method testFollowRedirect.

private void testFollowRedirect(HttpMethod method, HttpMethod expectedMethod, int statusCode, int expectedStatus, int expectedRequests, String location, String expectedURI) throws Exception {
    String s;
    if (createBaseServerOptions().isSsl() && location.startsWith("http://")) {
        s = "https://" + location.substring("http://".length());
    } else {
        s = location;
    }
    String t;
    if (createBaseServerOptions().isSsl() && expectedURI.startsWith("http://")) {
        t = "https://" + expectedURI.substring("http://".length());
    } else {
        t = expectedURI;
    }
    AtomicInteger numRequests = new AtomicInteger();
    server.requestHandler(req -> {
        HttpServerResponse resp = req.response();
        if (numRequests.getAndIncrement() == 0) {
            resp.setStatusCode(statusCode);
            if (s != null) {
                resp.putHeader(HttpHeaders.LOCATION, s);
            }
            resp.end();
        } else {
            assertEquals(t, req.absoluteURI());
            assertEquals("foo_value", req.getHeader("foo"));
            assertEquals(expectedMethod, req.method());
            resp.end();
        }
    });
    startServer();
    client.request(method, DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, "/somepath", resp -> {
        assertEquals(resp.request().absoluteURI(), t);
        assertEquals(expectedRequests, numRequests.get());
        assertEquals(expectedStatus, resp.statusCode());
        testComplete();
    }).putHeader("foo", "foo_value").setFollowRedirects(true).end();
    await();
}
Also used : VertxException(io.vertx.core.VertxException) MultiMap(io.vertx.core.MultiMap) TimeoutException(java.util.concurrent.TimeoutException) Context(io.vertx.core.Context) InetAddress(java.net.InetAddress) HttpFrame(io.vertx.core.http.HttpFrame) HttpVersion(io.vertx.core.http.HttpVersion) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Map(java.util.Map) TestLoggerFactory(io.vertx.test.netty.TestLoggerFactory) HttpHeaders(io.vertx.core.http.HttpHeaders) HttpResponseStatus(io.netty.handler.codec.http.HttpResponseStatus) UUID(java.util.UUID) Future(io.vertx.core.Future) FileNotFoundException(java.io.FileNotFoundException) Nullable(io.vertx.codegen.annotations.Nullable) CountDownLatch(java.util.concurrent.CountDownLatch) List(java.util.List) Buffer(io.vertx.core.buffer.Buffer) DefaultHttpHeaders(io.netty.handler.codec.http.DefaultHttpHeaders) HttpServerResponse(io.vertx.core.http.HttpServerResponse) AbstractVerticle(io.vertx.core.AbstractVerticle) WorkerContext(io.vertx.core.impl.WorkerContext) UnsupportedEncodingException(java.io.UnsupportedEncodingException) HttpClient(io.vertx.core.http.HttpClient) NetSocket(io.vertx.core.net.NetSocket) IntStream(java.util.stream.IntStream) HeadersAdaptor(io.vertx.core.http.impl.HeadersAdaptor) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) HashMap(java.util.HashMap) CompletableFuture(java.util.concurrent.CompletableFuture) TestUtils.assertNullPointerException(io.vertx.test.core.TestUtils.assertNullPointerException) AtomicReference(java.util.concurrent.atomic.AtomicReference) Function(java.util.function.Function) ArrayList(java.util.ArrayList) HttpClientRequest(io.vertx.core.http.HttpClientRequest) HttpClientResponse(io.vertx.core.http.HttpClientResponse) OutputStreamWriter(java.io.OutputStreamWriter) Assume(org.junit.Assume) AsyncResult(io.vertx.core.AsyncResult) HttpClientOptions(io.vertx.core.http.HttpClientOptions) HttpConnection(io.vertx.core.http.HttpConnection) BufferedWriter(java.io.BufferedWriter) Vertx(io.vertx.core.Vertx) FileOutputStream(java.io.FileOutputStream) Test(org.junit.Test) File(java.io.File) TimeUnit(java.util.concurrent.TimeUnit) Consumer(java.util.function.Consumer) EventLoopContext(io.vertx.core.impl.EventLoopContext) URLEncoder(java.net.URLEncoder) Rule(org.junit.Rule) DeploymentOptions(io.vertx.core.DeploymentOptions) HttpMethod(io.vertx.core.http.HttpMethod) HttpServerOptions(io.vertx.core.http.HttpServerOptions) InternalLoggerFactory(io.netty.util.internal.logging.InternalLoggerFactory) Handler(io.vertx.core.Handler) Collections(java.util.Collections) TestUtils.assertIllegalStateException(io.vertx.test.core.TestUtils.assertIllegalStateException) TemporaryFolder(org.junit.rules.TemporaryFolder) TestUtils.assertIllegalArgumentException(io.vertx.test.core.TestUtils.assertIllegalArgumentException) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) HttpServerResponse(io.vertx.core.http.HttpServerResponse)

Example 7 with HttpMethod

use of io.vertx.core.http.HttpMethod in project java-chassis by ServiceComb.

the class RestUtils method httpDo.

public static void httpDo(RequestContext requestContext, Handler<RestResponse> responseHandler) {
    HttpClientWithContext vertxHttpClient = HttpClientPool.INSTANCE.getClient();
    vertxHttpClient.runOnContext(httpClient -> {
        IpPort ipPort = requestContext.getIpPort();
        HttpMethod httpMethod = requestContext.getMethod();
        RequestParam requestParam = requestContext.getParams();
        if (ipPort == null) {
            LOGGER.error("request address is null");
            responseHandler.handle(new RestResponse(requestContext, null));
            return;
        }
        StringBuilder url = new StringBuilder(requestContext.getUri());
        String queryParams = requestParam.getQueryParams();
        if (!queryParams.isEmpty()) {
            url.append(url.lastIndexOf("?") > 0 ? "&" : "?").append(queryParams);
        }
        HttpClientRequest httpClientRequest = httpClient.request(httpMethod, ipPort.getPort(), ipPort.getHostOrIp(), url.toString(), response -> {
            responseHandler.handle(new RestResponse(requestContext, response));
        });
        httpClientRequest.setTimeout(ServiceRegistryConfig.INSTANCE.getRequestTimeout()).exceptionHandler(e -> {
            LOGGER.error("{} {} fail, endpoint is {}:{}, message: {}", httpMethod, url.toString(), ipPort.getHostOrIp(), ipPort.getPort(), e.getMessage());
            responseHandler.handle(new RestResponse(requestContext, null));
        });
        addDefaultHeaders(httpClientRequest);
        if (requestParam.getHeaders() != null && requestParam.getHeaders().size() > 0) {
            for (Map.Entry<String, String> header : requestParam.getHeaders().entrySet()) {
                httpClientRequest.putHeader(header.getKey(), header.getValue());
            }
        }
        if (requestParam.getCookies() != null && requestParam.getCookies().size() > 0) {
            StringBuilder stringBuilder = new StringBuilder();
            for (Map.Entry<String, String> cookie : requestParam.getCookies().entrySet()) {
                stringBuilder.append(cookie.getKey()).append("=").append(cookie.getValue()).append("; ");
            }
            httpClientRequest.putHeader("Cookie", stringBuilder.toString());
        }
        if (httpMethod != HttpMethod.GET && requestParam.getBody() != null && requestParam.getBody().length > 0) {
            httpClientRequest.end(Buffer.buffer(requestParam.getBody()));
        } else {
            httpClientRequest.end();
        }
    });
}
Also used : HttpClientRequest(io.vertx.core.http.HttpClientRequest) HttpClientWithContext(io.servicecomb.foundation.vertx.client.http.HttpClientWithContext) IpPort(io.servicecomb.foundation.common.net.IpPort) MultiMap(io.vertx.core.MultiMap) HashMap(java.util.HashMap) Map(java.util.Map) HttpMethod(io.vertx.core.http.HttpMethod)

Aggregations

HttpMethod (io.vertx.core.http.HttpMethod)7 HttpClientRequest (io.vertx.core.http.HttpClientRequest)5 MultiMap (io.vertx.core.MultiMap)4 Buffer (io.vertx.core.buffer.Buffer)4 HashMap (java.util.HashMap)4 Handler (io.vertx.core.Handler)3 ArrayList (java.util.ArrayList)3 Test (org.junit.Test)3 Nullable (io.vertx.codegen.annotations.Nullable)2 Future (io.vertx.core.Future)2 Vertx (io.vertx.core.Vertx)2 HttpClient (io.vertx.core.http.HttpClient)2 HttpClientResponse (io.vertx.core.http.HttpClientResponse)2 HttpServerOptions (io.vertx.core.http.HttpServerOptions)2 JsonArray (io.vertx.core.json.JsonArray)2 JsonObject (io.vertx.core.json.JsonObject)2 NetSocket (io.vertx.core.net.NetSocket)2 Map (java.util.Map)2 CompletableFuture (java.util.concurrent.CompletableFuture)2 DefaultHttpHeaders (io.netty.handler.codec.http.DefaultHttpHeaders)1