Search code examples
javalagom

Lagom Send custom header


I'm working on Lagom POC on sending POST request to Non lagom service with custom Header. In my case I'm trying to hit postman-echo to test the custom header. However, it looks the headers are not set though I made code changes accordingly:

public CompletionStage<DsapAuthorizationResponse> hitAPI(AuthorizationRequest request) {
            DsapWSRequest dsapWSRequest = new DsapWSRequest();
            dsapWSRequest.username = request.username;
            dsapWSRequest.password = request.password;
            CompletionStage<DsapAuthorizationResponse> dsapresponse = dsapExternalService
                    .authenticate()
                    .handleRequestHeader(requestHeader -> {
                        requestHeader.withHeader("Authorization","Basic mncndsjna");
                        System.out.println("My Headers>>>>>>>> " + requestHeader);
                        return requestHeader;
                    })
                    .handleResponseHeader((responseHeader,b) -> {
                        System.out.println("RESPonse Header >>>>>>> : "+responseHeader);
                        return b;
                    })
                    .invoke(dsapWSRequest);
            return dsapresponse;

        }

In the above code header authorization is not set in the request. I am not getting this header in the echo which is mapped correctly in my POJO.

here is the complete code from my GitHub https://github.com/sourabhsar/Lagom-Unmanaged-Service-Demo/tree/poc/lagom-request-response

I followed the steps mentioned here: https://groups.google.com/forum/#!topic/lagom-framework/yvKmqvtZWFs

and also followed few other blogs/articles. However so far I haven't found any blog which they are sending request to unmanaged external service with custom header. I'm not sure whats wrong in my code.


Solution

  • requestHeader.withHeader returns a new object with the added header, but the code you have written returns the original requestHeader object. In general, many Lagom APIs follow a principle of using immutable objects, with methods that return a new, modified instance, rather than changing the instance the method is called on.

    Try this:

    .handleRequestHeader(requestHeader -> {
        RequestHeader modifiedRequestHeader =
            requestHeader.withHeader("Authorization","Basic mncndsjna");
        System.out.println("My Headers>>>>>>>> " + modifiedRequestHeader);
        return modifiedRequestHeader;
    })