AndroidNetworking.post() 在通过字符串返回之前不等待响应数据

AndroidNetworking.post() doesn't wait the response data before returning via string

我在 aar 模块中有一个函数需要使用 AndroidNetworking 等待 onResponse()onError() 响应。输出是 return 在等待收到的任何响应之前首先执行。我在等待对我的应用程序 return 的响应时遇到问题。我还在函数上使用了 synchronized 。这是我模块上的代码

 public static synchronized String getActivationData(final Context context, final String api, final String base64Header, final String endpoint, final JSONObject body) {

    final String[] result = {null};

    new Thread(new Runnable() {
        @Override
        public void run() {
            StrictMode.ThreadPolicy policy =
                    new StrictMode.ThreadPolicy.Builder().permitAll().build();
            StrictMode.setThreadPolicy(policy);


            String baseURL = null;

            if (api.equalsIgnoreCase("LOCAL")) {
                baseURL = Environments.getMarkLocalAPI();
            } else if (api.equalsIgnoreCase("DEVELOPMENT")) {
                baseURL = Environments.getDevelopmentAPI();
            } else if (api.equalsIgnoreCase("STAGING")) {
                baseURL = Environments.getStagingAPI();
            } else if (api.equalsIgnoreCase("DEPLOYMENT")) {
                baseURL = Environments.getDeploymentAPI();
            }

            final String finalBaseURL = baseURL;


            OkHttpClient okHttpClient = new OkHttpClient().newBuilder()
                    .connectTimeout(15, TimeUnit.SECONDS)
                    .readTimeout(15, TimeUnit.SECONDS)
                    .writeTimeout(15, TimeUnit.SECONDS)
                    .build();

            AndroidNetworking.initialize(context, okHttpClient);

            AndroidNetworking.post(finalBaseURL + endpoint)
                    .setPriority(Priority.HIGH)
                    .addJSONObjectBody(body)
                    .addHeaders("Project", base64Header)
                    .addHeaders("Content-Type", "application/json")
                    .build()
                    .getAsJSONObject(new JSONObjectRequestListener() {

                        @Override
                        public void onResponse(JSONObject response) {
                            result[0] = String.valueOf(response);
                        }

                        @Override
                        public void onError(ANError anError) {
                            if (anError.getErrorCode() != 0) {
                                result[0] = String.valueOf(anError.getErrorDetail());

                            } else {
                                result[0] = String.valueOf(anError.getErrorDetail());
                            }
                        }
                    });
            Log.i("data", result[0]);
        }
    }).start();
    return result[0];
}

并通过以下方式在我的应用程序上调用函数:

String data = ActivationResponseV2.getActivationData(getContext(), "LOCAL", header, "/sample/response", jsonObject);

我可以知道我做错了什么吗?。谢谢!

响应在 post 调用之外返回:要处理此问题,您可以将回调方法传递给您的函数,以便在结果就绪时使用它。

public static void getActivationData(final Context context, 
       final String api, final String base64Header, final String endpoint,
         final JSONObject body, Callable<Void> methodParam) { 
            String baseURL = null;

            if (api.equalsIgnoreCase("LOCAL")) {
                baseURL = Environments.getMarkLocalAPI();
            } else if (api.equalsIgnoreCase("DEVELOPMENT")) {
                baseURL = Environments.getDevelopmentAPI();
            } else if (api.equalsIgnoreCase("STAGING")) {
                baseURL = Environments.getStagingAPI();
            } else if (api.equalsIgnoreCase("DEPLOYMENT")) {
                baseURL = Environments.getDeploymentAPI();
            } 


            OkHttpClient okHttpClient = new OkHttpClient().newBuilder()
                    .connectTimeout(15, TimeUnit.SECONDS)
                    .readTimeout(15, TimeUnit.SECONDS)
                    .writeTimeout(15, TimeUnit.SECONDS)
                    .build();

            AndroidNetworking.initialize(context, okHttpClient);

            AndroidNetworking.post(baseURL + endpoint)
                    .setPriority(Priority.HIGH)
                    .addJSONObjectBody(body)
                    .addHeaders("Project", base64Header)
                    .addHeaders("Content-Type", "application/json")
                    .build()
                    .getAsJSONObject(new JSONObjectRequestListener() {

                        @Override
                        public void onResponse(JSONObject response) {
                            //result[0] = String.valueOf(response);
                            methodParam.call(String.valueOf(response));
                        }

                        @Override
                        public void onError(ANError anError) {
                            if (anError.getErrorCode() != 0) {
                               // result[0] = String.valueOf(anError.getErrorDetail()); 
                            } else {
                                //result[0] = String.valueOf(anError.getErrorDetail());
                            }
                            methodParam.call(String.valueOf(anError.getErrorDetail()));
                        }
                    });
             // Log.i("data", result[0]); 
  }

像下面这样使用

ActivationResponseV2.getActivationData(getContext(), "LOCAL", header, 
           "/sample/response", jsonObject, new Callable<Void>() {
                public Void call(String data) {
                    //...Consume data here
                    return null;
                });

我已经用ANRequest完成了。阅读 this 文件后。我尝试复制它并得到了我想要的输出。

这是代码:

 public static synchronized String getActivationData(final Context context, final String api, final String base64Header, final String endpoint, final JSONObject body) {

    final String[] result = {null};

    String baseURL = null;

    if (api.equalsIgnoreCase("LOCAL")) {
        baseURL = Environments.getMarkLocalAPI();
    } else if (api.equalsIgnoreCase("DEVELOPMENT")) {
        baseURL = Environments.getDevelopmentAPI();
    } else if (api.equalsIgnoreCase("STAGING")) {
        baseURL = Environments.getStagingAPI();
    } else if (api.equalsIgnoreCase("DEPLOYMENT")) {
        baseURL = Environments.getDeploymentAPI();
    }

    final String finalBaseURL = baseURL;


    OkHttpClient okHttpClient = new OkHttpClient().newBuilder()
            .connectTimeout(15, TimeUnit.SECONDS)
            .readTimeout(15, TimeUnit.SECONDS)
            .writeTimeout(15, TimeUnit.SECONDS)
            .build();

    AndroidNetworking.initialize(context, okHttpClient);

    ANRequest request = AndroidNetworking.post(finalBaseURL + endpoint)
            .setPriority(Priority.HIGH)
            .addJSONObjectBody(body)
            .addHeaders("Project", base64Header)
            .addHeaders("Content-Type", "application/json")
            .build();


    ANResponse response = request.executeForJSONObject();

    if (response.isSuccess()) {
        result[0] = String.valueOf(response.getResult());
        Log.d(TAG, "response : " + result[0]);
    } else {
        ANError error = response.getError();
        Log.d(TAG, "response : " + error);
    }

    return result[0];
    }
}

编码愉快!