1

I'm new to Play framework, and trying to use JavaWS to make a call to a RESTful API. I've been struggling a lot with it. This is what I have so far:

This code is based on the JavaWS documentation (which I found quite confusing), and is meant to make the request. I think it works by returing a completion stage of an 'ok' result which contains a string that is the result of converting the response to text.

import javax.inject.Inject;

import com.fasterxml.jackson.databind.JsonNode;
import play.mvc.*;
import play.libs.ws.*;
import java.util.concurrent.*;

import static play.mvc.Results.ok;

public class MyClient implements WSBodyReadables, WSBodyWritables {
    private final WSClient ws;

    @Inject
    public MyClient() {
        this.ws = ws;
    }

    public CompletionStage<Result> index() {
        return ws.url("http://example.com").get().thenApply(response ->
                ok(response.asText())
        );
    }

}

This code is then called from a controller:

public Result call(){
    MyClient client = new MyClient();

    try {
        return client.index()
                .toCompletableFuture()
                .get();
    } catch(Exception e){
        Logger.error("ah fuck");
    }
    return internalServerError();
}

I'm currently getting an error which says "variable ws might not have been initialized" which makes sense because I did not initialize ws. I can't figure out how to properly initialize a WSClient instance, nor do I really understand what comes after that. Any help would be greatly appreciated.

Thanks.

  • inject `@Inject WSClient ws;` in your controller and then pass ws instance to `MyClient` class and access it from there. `MyClient client = new MyClient(this.ws);` check https://www.playframework.com/documentation/2.5.x/JavaWS – rkj Jul 15 '18 at 03:54

2 Answers2

0

Alternatively, you can use Feign library from Netflix to create Rest client.

Delphi
  • 71
  • 1
  • 8
0

@rkj had it right:

inject @Inject WSClient ws; in your controller and then pass ws instance to >MyClient class and access it from there. MyClient client = new MyClient(this.ws);

That plus a few little bugs and it worked. Thanks!