Search code examples
javamicronaut

Micronaut: how to set an HttpClient URL after injection


I have the following method:


    public HttpResponse<String> sendMessage(@NonNull String url, @NonNull String message) {
            try (HttpClient client = HttpClient.create(new URL(url))) { ... }
    }

Basically, what I want to achieve is to create the HttpClient with a URL that comes as a parameter to the method. It cannot be a property in a config file since it depends on some external conditions. If I check the docs for the HttpClient.create() method it says that it should not be used within a Micronaut environment, and that the client should be injected instead. However, the problem is that if it's injected I cannot initialize it with my custom URL.

Another problem is that if I keep it with the HttpClient.create() method, if I want to unit test the class, I cannot mock the HttpClient. The best option would be to inject it via constructor to be able to create the tests.

What options do I have? I haven't been able to find this type of initialization. It looks like everyone uses a fix URL? 😅

Thanks!


Solution

  • I'll answer it myself. Apparently, you can specify in the request passed to the HttpClient methods (retrieve, exchange, etc.) both the relative and full URLs. So it doesn't matter what you put when you inject, instantiate the client.