美文网首页
Okhttp如何在主线程上自定义回应回调?

Okhttp如何在主线程上自定义回应回调?

作者: 浅笑19 | 来源:发表于2020-05-23 18:03 被阅读0次

    我创建了一个帮助程序类来处理我的应用程序中的所有http调用。这是一个okhttp的简单单例包装,看起来像这样(我省略了一些不重要的部分):

    public class HttpUtil {
    
        private OkHttpClient client;
        private Request.Builder builder;
    
        ...
    
        public void get(String url, HttpCallback cb) {
            call("GET", url, cb);
        }
    
        public void post(String url, HttpCallback cb) {
            call("POST", url, cb);
        }
    
        private void call(String method, String url, final HttpCallback cb) {
            Request request = builder.url(url).method(method, method.equals("GET") ? null : new RequestBody() {
                // don't care much about request body
                @Override
                public MediaType contentType() {
                    return null;
                }
    
                @Override
                public void writeTo(BufferedSink sink) throws IOException {
    
                }
            }).build();
    
            client.newCall(request).enqueue(new Callback() {
                @Override
                public void onFailure(Request request, Throwable throwable) {
                    cb.onFailure(null, throwable);
                }
    
                @Override
                public void onResponse(Response response) throws IOException {
                    if (!response.isSuccessful()) {
                        cb.onFailure(response, null);
                        return;
                    }
                    cb.onSuccess(response);
                }
            });
        }
    
    
        public interface HttpCallback  {
    
            /**
             * called when the server response was not 2xx or when an exception was thrown in the process
             * @param response - in case of server error (4xx, 5xx) this contains the server response
             *                 in case of IO exception this is null
             * @param throwable - contains the exception. in case of server error (4xx, 5xx) this is null
             */
            public void onFailure(Response response, Throwable throwable);
    
            /**
             * contains the server response
             * @param response
             */
            public void onSuccess(Response response);
        }
    
    }
    

    然后使用方法:

            HttpUtil.get(url, new HttpUtil.HttpCallback() {
                @Override
                public void onFailure(Response response, Throwable throwable) {
                    // handle failure
                }
    
                @Override
                public void onSuccess(Response response) {
                    // <-------- Do some view manipulation here
                }
            });
    

    -onSuccess- 代码运行时引发异常:

    android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.
    Only the original thread that created a view hierarchy can touch its views.
    都是因为http请求是在子线程进行的,ui绘制和 Toast 都是在主线程
    解决方法:
    在相关代码前加上

    Looper.prepare();
    Toast.makeText(getContext(),"请求成功 :" + response.body().string() ,Toast.LENGTH_LONG).show();
    //do ……
    Looper.loop();
    

    即可

    相关文章

      网友评论

          本文标题:Okhttp如何在主线程上自定义回应回调?

          本文链接:https://www.haomeiwen.com/subject/ogelahtx.html