最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

java - How can I change the code so as not to create a new Callback over and over again? - Stack Overflow

programmeradmin7浏览0评论
public static void GenerateToken(Callback callback) {
        try {
            Request request = getRequest();
            client.newCall(request).enqueue(new okhttp3.Callback() {
                @Override
                public void onFailure(@NonNull Call call, @NonNull IOException e) {
                    callback.onError(e);
                }

                @Override
                public void onResponse(@NonNull Call call, @NonNull Response response) {
                    try (ResponseBody responseBody = response.body()) { //автоматическоое закрытие
                        if (response.isSuccessful() && responseBody != null) {
                            JSONObject jsonResponse = new JSONObject(responseBody.string());
                            String accessToken = jsonResponse.optString("access_token", null);
                            callback.onResponse(accessToken);
                        }
                    }catch (Exception e) {
                        callback.onError(new IOException("Unexpected response: " + response));
                    }
                }
            });

        } catch (Exception e) {
            callback.onError(e);

        }
    }

I want to change the infinite stream creation, but I don't understand how?

I expected that when creating 1 thread, I would always be able to use it, but instead I have new threads created every time, new okhttp3.Callback(), I would like to create it once and then use it

发布评论

评论列表(0)

  1. 暂无评论