完成网络操作后,OkHttp会在原始类中触发回调

时间:2015-12-10 04:12:18

标签: android okhttp

这是一个场景:我有一个名为try { quantity = Integer.parseInt(quantityCell.getText().toString()); } catch (NumberFormatException nfe) { Toast.makeText(getApplicationContext(), "Please enter a valid number", Toast.LENGTH_LONG).show(); quantity = savedQuantity; } 的Activity,调用一个名为MainActivity的OkHttp包装类来在后台执行网络发布:

NetworkManager

然后,在// In MainActivity NetworkManager manager = new NetworkManager(); try { manager.post("http://www.example.com/api/", reqObj); // reqObj is a JSONObject } catch(IOException ioe) { Log.e(TAG, ioe.getMessage()); } 中,我以异步模式执行POST操作:

NetworkManager

我想要实现的是在网络POST成功或失败后调用public class NetworkManager { static String TAG = "NetworkManager"; public static final MediaType JSON = MediaType.parse("application/json; charset=utf-8"); OkHttpClient client = new OkHttpClient(); void post(String url, JSONObject json) throws IOException { //RequestBody body = RequestBody.create(JSON, json); try { JSONArray array = json.getJSONArray("d"); RequestBody body = new FormEncodingBuilder() .add("m", json.getString("m")) .add("d", array.toString()) .build(); Request request = new Request.Builder() .url(url) .post(body) .build(); // Asynchronous Mode client.newCall(request).enqueue(new Callback() { @Override public void onFailure(Request request, IOException e) { Log.e(TAG, e.toString()); // what should I put here? } @Override public void onResponse(Response response) throws IOException { Log.w(TAG, response.body().string()); // what should I put here? } }); } catch (JSONException jsone) { Log.e(TAG, jsone.getMessage()); } } } 中的函数。我怎样才能做到这一点?

1 个答案:

答案 0 :(得分:2)

您可以使用onFailureonResponse创建一个界面,然后让YourActivity实现它。并且,在NetworkManager尝试使用侦听器通知YourActivity

       // MainActivity implements NetworkListener 
        NetworkManager manager = new NetworkManager();
        manager.setOnNetWorkListener(this);
        try {
            manager.post("http://www.example.com/api/", reqObj); // reqObj is a JSONObject
        } catch(IOException ioe) {
            Log.e(TAG, ioe.getMessage());
        }
        void onFailure(Request request, IOException e) {
             // call your activity methods
        }
        void onResponse(Response response) {
             // call your activity methods  
        }

        // ======NetworkManager class============
        public class NetworkManager {
            static String TAG = "NetworkManager";
            public static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");
            OkHttpClient client = new OkHttpClient();
            public NetworkListenerv listener;
            public void setOnNetWorkListener(NetworkListener listener) {
                this.listener = listener
            }
            // Asynchronous Mode
            client.newCall(request).enqueue(new Callback() {
                @Override
                public void onFailure(Request request, IOException e) {
                    Log.e(TAG, e.toString());
                    // what should I put here?
                    if (listener != null) {
                        listener.onFailure(request, e);
                    }
                }

                @Override
                public void onResponse(Response response) throws IOException {
                    Log.w(TAG, response.body().string());
                    // what should I put here?
                     if (listener != null) {
                        listener.onResponse(response);
                    }
                }
            });

    // Your interface;
     public interface NetworkListener {
        void onFailure(Request request, IOException e);
        void onResponse(Response response);
    }