Android Okhttp使用响应

Android Okhttp使用响应,android,asynchronous,okhttp,Android,Asynchronous,Okhttp,我使用一个异步的Okhttp做请求,然后使用响应填充UI 我的想法是在主线程中等待响应,然后开始新的活动。这是最好的方式吗?如果是这样,我如何等待并访问主线程中响应的解析数据 主要活动: public void sendMessage(View view) throws IOException, InterruptedException { Intent intent = new Intent(this, DisplayMessageActivity.class); ...

我使用一个异步的Okhttp做请求,然后使用响应填充UI

我的想法是在主线程中等待响应,然后开始新的活动。这是最好的方式吗?如果是这样,我如何等待并访问主线程中响应的解析数据

主要活动:

public void sendMessage(View view) throws IOException, InterruptedException {
    Intent intent = new Intent(this, DisplayMessageActivity.class);
    ...
    HttpHelper client = new HttpHelper();
    String response = client.get("https://www.google.com");
    ...
    intent.putExtra(EXTRA_MESSAGE, message+"\nresponse:\n"+response);
    Bundle b = new Bundle();
    b.putStringArray("DATA_GET", client.dataOut);
    intent.putExtras(b);
    startActivity(intent);
}
HttpHelper类:

public class HttpHelper {

    OkHttpClient client = new OkHttpClient();
    String[] dataOut;

    String get(String url) throws IOException, InterruptedException {

        Request request = new Request.Builder()
                .url(url)
                .build();

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

            @Override public void onResponse(Response response) throws IOException{
                if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);

                // parsing response
                dataOut = ...;
            }
        });

        return "done";
    }
}

谢谢,

不,这是一种不好的方式。我建议使用
改型
,它将在后台线程上为您处理大多数样板网络内容,并在完成后通过回调为您提供响应。

您能解释一下原因吗?使用okhttp和enqueue函数,请求不会在主线程中处理。非常感谢,对不起,我发了两封邮件,但是没有给你贴上@pat的标签