美文网首页
网络访问组件的思考五(response封装)

网络访问组件的思考五(response封装)

作者: zhaoyubetter | 来源:发表于2017-03-16 19:14 被阅读60次

    具体代码:
    https://github.com/zhaoyubetter/basenet

    okhttp 中的Response类

    从okhttp的回调接口可发现,在回调中,传入了 response参数,response表示响应,下为 okhttp reponse 类代码片段

    public final class Response implements Closeable {
      final Request request;
      final Protocol protocol;
      final int code;
      final String message;
      final Handshake handshake;
      final Headers headers;
      final ResponseBody body;
      final Response networkResponse;
      final Response cacheResponse;
      final Response priorResponse;
      final long sentRequestAtMillis;
      final long receivedResponseAtMillis;
    

    volley 中同样也有,只不过需要复写方法来获取;

    参考okhttp 实现自己的response

    不考虑封装这么多参数,我们这边只封装了几个基本的参数,如下:

    public class Response<T> {
        /**
         * 此次的请求
         */
        public AbsRequest request;
        /**
         * 响应header
         */
        public Map<String, String> responseHeader;
        /**
         * 响应体
         */
        public T responseBody;
        /**
         * 状态码
         */
        public int statusCode;
    

    响应头是必须得,接口共用的信息,我们一般都放在这里了;然后修改网络请求的回调接口:

    public abstract class AbsRequestCallBack<T> {
        public void onSuccess(Response<T> response) {
        }
    
        public void onFailure(Throwable e) {
        }
    
        public void onProgressUpdate(long contentLength, long bytesRead, boolean done) {
        }
    }
    

    具体实现(VolleyRequest):

    @Override
    protected Response<String> parseNetworkResponse(NetworkResponse response) {
            Response<String> stringResponse = super.parseNetworkResponse(response);
            if (mCallBack != null) {
                    mCallBack.onSuccess(new lib.basenet.response.Response(VolleyRequest.this, response.headers, stringResponse.result));
            }
            return stringResponse;
    }
    

    具体实现(Okhttp)

    @Override
    public void onResponse(Call call, Response response) throws IOException {
            if (null != mCallBack) {
                    headerMap = getResponseHeaders(response);
                    if (response.isSuccessful()) {
                            isSuccess = true;
                            returnBody = response.body().string();    // 字符串响应体
                            mCallBack.onSuccess(new lib.basenet.response.Response(OkHttpRequest.this, headerMap, returnBody));
                    } else {
                            isSuccess = false;
                            returnBody = response.code() + " " + response.message();
                            mCallBack.onFailure(new Exception(returnBody));
                    }
                }
            }
    

    相关文章

      网友评论

          本文标题:网络访问组件的思考五(response封装)

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