我想问一下是否可以使用OkHttp的enqueue
方法来接收异步站点的内容。
我目前使用execute
方法来接收不同API站点的内容(在我的情况下,它始终是JSONObject或返回的JSON中作为String的特定值。有关当前方法,请参见下面的代码)。
我现在尝试使用enqueue方法来异步接收内容,但是我没有异步方法的经验,因此,我不知道如何(甚至更多IF)使用该方法的解决方案。 / p>
如果您可以通过该方法返回值,则Example on the wiki并不会真正显示出来。
我使用的当前方法:
public String getImgLink(String endpoint) throws IOException{
Request request = new Request.Builder()
.url("https://example.com/api/" + endpoint)
.build();
// I want to change this to enqueue if possible
Response response = CLIENT.newCall(request).execute();
try(ResponseBody body = response.body()){
if(!response.isSuccessful()) throw new IOException(Unexpected code " + response);
return new JSONObject(Objects.requireNonNull(body).string()).get("url").toString();
}
}