okhttp3 如何从异步 GET 调用中获取 return 值

okhttp3 how to return value from async GET call

我正在 Android 工作室中实施助手 class 以服务 Activity

public void getLastId()
{
    //init OkHttpClient
    OkHttpClient client = new OkHttpClient();

    //backend url
    Request request = new Request.Builder()
            .url("http://192.168.1.102:8080/aquabackend/public/customers/lastid")
            .build();


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

        }

        @Override
        public void onResponse(Call call, Response response) throws IOException {

            String jsonData = response.body().string();

            try {
                JSONObject jobject = new JSONObject(jsonData);
                String id = jobject.getString("id");

                //increment current id +1
                String last_id = String.valueOf(Integer.parseInt(id)+1);
                Log.i("new id", last_id);

            } catch (Exception e) {
                    e.printStackTrace();
            }
            //Log.i("ok", response.body().string());
        }
    });

我的函数调用在 activity class

Helper helper = new Helper();
helper.getLastId();
//I want to get method to return lastId and then manipulate with the data

如何使方法 return 成为 id 的值?

创建界面。

public interface Result{
   void getResult(String id);
}

现在,将接口作为参数传递给方法。

 Helper helper = new Helper();
      helper.getLastId(new Result(){
        @Override
        void getResult(String id){

        }
});

在你的方法中:

public void getLastId(final Result result)
{
    //init OkHttpClient
    OkHttpClient client = new OkHttpClient();

    //backend url
    Request request = new Request.Builder()
            .url("http://192.168.1.102:8080/aquabackend/public/customers/lastid")
            .build();


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

        }

        @Override
        public void onResponse(Call call, Response response) throws IOException {

            String jsonData = response.body().string();

            try {
                JSONObject jobject = new JSONObject(jsonData);
                String id = jobject.getString("id");

                //increment current id +1
                String last_id = String.valueOf(Integer.parseInt(id)+1);
                Log.i("new id", last_id);
                result.getResult(last_id);

            } catch (Exception e) {
                    e.printStackTrace();
            }
            //Log.i("ok", response.body().string());
        }
    });

您必须为其创建 interface

public interface getResponse {

     void getJsonResponse(final String id);

}

在您的代码中:

public void getLastId(fianl getResponse response)
{
    //init OkHttpClient
    OkHttpClient client = new OkHttpClient();

    //backend url
    Request request = new Request.Builder()
            .url("http://192.168.1.102:8080/aquabackend/public/customers/lastid")
            .build();


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

        }

        @Override
        public void onResponse(Call call, Response response) throws IOException {

            String jsonData = response.body().string();

            try {
                JSONObject jobject = new JSONObject(jsonData);
                String id = jobject.getString("id");

                //increment current id +1
                String last_id = String.valueOf(Integer.parseInt(id)+1);
                Log.i("new id", last_id);
if(response!=null){
response.getJsonResponse(last_id)
}
            } catch (Exception e) {
                    e.printStackTrace();
            }
            //Log.i("ok", response.body().string());
        }
    });

在 Activity 中:

 public class HomeActivity extends AppCompatActivity  {
 @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    Helper helper = new Helper();
      helper.getLastId(new getResponse(){
            @Override
            void getJsonResponse(String id){

            }
    });
}}
    }

由于它是一个异步过程,您将无法 return 来自方法本身的值。但是,您可以使用回调在异步过程完成后为您提供值。以下是您可能希望如何执行此操作的示例。

public interface GetLastIdCallback {
    void lastId(String id);
}

您将修改 getLastId 如下:

public void getLastId(GetLastIdCallback idCallback) {
    ...
    String last_id = String.valueOf(Integer.parseInt(id)+1);
    idCallback.lastId(last_id);
    ...

}

您的助手 class 用法现在如下所示:

Helper helper = new Helper();
helper.getLastId(new GetLastIdCallback() {
     @Override
     public void lastId(String id) {
         // Do something with your id
     }
});

我建议让您的回调比我上面建议的更通用一些。它可能看起来像这样:

public interface GenericCallback<T> {
    void onValue(T value);
}

...

Helper helper = new Helper();
helper.getLastId(new GenericCallback<String>() {
    @Override
    public void onValue(String value) {
        // Do something
    }
});

如果您使用上述界面,您将能够使用任何 return 类型。