Request body gets lost in http get request. (Java-Spark)

Viewed 44

When I sent the following request to my program, the body gets lost:

GET http://localhost:4567/contacts/get-all

Authorization : test
Content-Type : text/plain

Hello

Java Code

public class Test {
    public static void main(String[] args) {
        Spark.get("contacts/get-all", (request, response) -> {
            checkForAuth(request);
            if (request != null) {
                System.out.println(request.body());
            }
            return "Success";
        });
    }

    protected static void checkForAuth(Request request) {
        if (request != null) {
            String authorization = request.headers("Authorization");
            System.out.println(authorization);
            if ("test".equals(authorization))
                return;
        }
        throw new Error("Not Authorized.");
    }
}

I expected the sysout to print Hello, but it only prints test (authorization header).

What am I doing wrong?

1 Answers

Based on documentation, you need to use * or : to make your request non-null e.g. :

Spark.get("contacts/:get-all", (request, response) -> {
            checkForAuth(request);
            if (request != null) {
                System.out.println(request.body());
            }
            return "Success";
        });

OR

Spark.get("contacts/*", (request, response) -> {
            checkForAuth(request);
            if (request != null) {
                System.out.println(request.body());
            }
            return "Success";
        });

& then call:

GET http://localhost:4567/contacts/get-all

This will print :

get-all

If you want to print, Hello, you have to append Hello to your get request.

Currently, it looks like request is coming as null & hence skipping executing System.out.println(request.body());

Related