如何使用OkHttp在本地变量中保存GET请求的结果?

时间:2019-01-16 00:45:28

标签: android get okhttp

我正在尝试用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);

谢谢...

1 个答案:

答案 0 :(得分:0)

我确定你是 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