【问题标题】:How to save result from a GET request with OkHttp in a local variable?如何将带有 OkHttp 的 GET 请求的结果保存在局部变量中?
【发布时间】:2019-01-16 00:45:27
【问题描述】:

我正在尝试用 Java 中的 OkHttp 发出 Get 请求。我使用异步线程成功实现了它,但我“卡”在 onResponse 函数中。我的意思是,除了这个函数,我不能在其他任何地方使用请求的结果。我该怎么做才能使这段代码工作?

            OkHttpClient client = new OkHttpClient();

            Request request = new Request.Builder()
                    .url("https://raw.github.com/square/okhttp/master/README.md")
                    .build();

            client.newCall(request).enqueue(new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    e.printStackTrace();
                }

                @Override
                public void onResponse(Call call, final Response response) throws IOException {
                        final String responseData = response.body().string();
                    LoginInscription.this.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            TextView tv = findViewById(R.id.txtString);
                            tv.setText(responseData);
                        }
                    });
                }
            });

            TextView tv = findViewById(R.id.txtString);
            String res = tv.getText().toString();

            System.out.println(res);

谢谢...

【问题讨论】:

    标签: android get okhttp


    【解决方案1】:

    我相信你的 System.out.println(res); 可能无法工作,因为 final String res 的范围在此之前结束。

    您可以声明可以更新的活动/类级别变量/方法onResponse()。 例如:

    @Override
    public void onResponse(Call call, Response response) throws IOException {
    
        final String myResponse = response.body().string();
        MainActivity.this.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                txtString.setText(myResponse);
            }   
        });
    }
    

    在以下位置获取更多示例: https://www.journaldev.com/13629/okhttp-android-example-tutorial

    【讨论】:

    • 谢谢。然后我可以将 txtString 中的文本分配给一个变量并根据需要使用它?
    • 没错。您也可以在 http 响应上调用一个方法,比如 updateTextAndDoSomeFun(String text)
    • 我更新了代码,但仍然无法在 res 中得到响应。你能告诉我有什么问题吗?
    • 您确定responseData 不为空/空吗?放一个Toast.makeText(getActivity(), (String)responseData, Toast.LENGTH_LONG).show(); 看看它是否实际上不是空/空的。另外,如果看到您的呼叫到达那里,您能否在方法onResponse 中进行调试。
    • 最后我做了第二个函数,我从 onResponse 调用它并将 responseData 作为参数传递。通过这个新函数,我能够将数据分配给我班级的成员变量。太好了,这正是我所需要的:随时随地访问我想要的数据。感谢您的帮助:)
    猜你喜欢
    • 1970-01-01
    • 2019-08-17
    • 1970-01-01
    • 1970-01-01
    • 2011-03-16
    • 1970-01-01
    • 2020-05-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多