co.easimart.vertx.http.HttpRequestUtil Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of vertx-util Show documentation
Show all versions of vertx-util Show documentation
Library provides utility classes for Vertx project development.
The newest version!
package co.easimart.vertx.http;
import org.apache.commons.lang3.tuple.Pair;
import org.slf4j.Logger;
import co.easimart.vertx.util.VertxHelper;
import io.vertx.core.AsyncResult;
import io.vertx.core.Future;
import io.vertx.core.Handler;
import io.vertx.core.buffer.Buffer;
import io.vertx.core.http.HttpClientRequest;
import io.vertx.core.http.HttpClientResponse;
import io.vertx.core.json.JsonObject;
/**
* Util class for call http request service.
*/
public final class HttpRequestUtil {
public static void expectResponse(String label,
HttpClientRequest request,
Buffer reqBuffer,
Handler> handler,
Logger logger) {
String uri = request.uri();
Future future = Future.future();
future.setHandler(handler);
// Handler exception
request.exceptionHandler(t -> {
logger.debug("[{}] Exception from http request to {}", label, uri, t);
if (future.isComplete()) return;
future.fail(t);
});
// Handler response
request.handler(res -> {
logger.debug("[{}] Headers of http response {} from {} - {}", label, res.statusCode(), uri, res.headers().entries());
future.complete(res);
});
// Send with request buffer
request.end(reqBuffer);
}
public static void receiveBuffer(String label, String uri, HttpClientResponse res, Handler> handler, Logger logger) {
Buffer body = Buffer.buffer();
res.handler(body::appendBuffer);
res.endHandler(r -> {
logger.debug("[{}] Http response from {} received - {}", label, uri, body);
// Read from response buffer
handler.handle(Future.succeededFuture(body));
});
}
public static void expectJson(String label,
HttpClientRequest request,
JsonObject reqJson,
Handler>> handler,
Logger logger) {
request.putHeader("Content-Type", "application/json");
request.putHeader("Accept", "application/json");
expectResponse(label, request, Buffer.buffer(reqJson.encode()), VertxHelper.ifSucceeded(res -> {
receiveBuffer(label, request.uri(), res, VertxHelper.ifSucceeded(buffer -> {
JsonObject body = new JsonObject(buffer.toString());
handler.handle(Future.succeededFuture(Pair.of(res, body)));
}, handler), logger);
}, handler), logger);
}
}