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.