Search in sources :

Example 1 with MIMEHeader

use of io.vertx.ext.web.MIMEHeader in project hono by eclipse.

the class AbstractHttpEndpoint method extractRequiredJsonPayload.

/**
 * Check the Content-Type of the request to be 'application/json' and extract the payload if this check was
 * successful.
 * <p>
 * The payload is parsed to ensure it is valid JSON and is put to the RoutingContext ctx with the
 * key {@link #KEY_REQUEST_BODY}.
 *
 * @param ctx The routing context to retrieve the JSON request body from.
 */
protected void extractRequiredJsonPayload(final RoutingContext ctx) {
    final MIMEHeader contentType = ctx.parsedHeaders().contentType();
    if (contentType == null) {
        ctx.response().setStatusMessage("Missing Content-Type header");
        ctx.fail(HttpURLConnection.HTTP_BAD_REQUEST);
    } else if (!HttpUtils.CONTENT_TYPE_JSON.equalsIgnoreCase(contentType.value())) {
        ctx.response().setStatusMessage("Unsupported Content-Type");
        ctx.fail(HttpURLConnection.HTTP_BAD_REQUEST);
    } else {
        try {
            if (ctx.getBody() != null) {
                ctx.put(KEY_REQUEST_BODY, ctx.getBodyAsJson());
                ctx.next();
            } else {
                ctx.response().setStatusMessage("Empty body");
                ctx.fail(HttpURLConnection.HTTP_BAD_REQUEST);
            }
        } catch (final DecodeException e) {
            ctx.response().setStatusMessage("Invalid JSON");
            ctx.fail(HttpURLConnection.HTTP_BAD_REQUEST);
        }
    }
}
Also used : MIMEHeader(io.vertx.ext.web.MIMEHeader) DecodeException(io.vertx.core.json.DecodeException)

Aggregations

DecodeException (io.vertx.core.json.DecodeException)1 MIMEHeader (io.vertx.ext.web.MIMEHeader)1