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

具体代码:
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 {
    /**
     * 此次的请求
     */
    public AbsRequest request;
    /**
     * 响应header
     */
    public Map responseHeader;
    /**
     * 响应体
     */
    public T responseBody;
    /**
     * 状态码
     */
    public int statusCode;

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

public abstract class AbsRequestCallBack {
    public void onSuccess(Response response) {
    }

    public void onFailure(Throwable e) {
    }

    public void onProgressUpdate(long contentLength, long bytesRead, boolean done) {
    }
}

具体实现(VolleyRequest):

@Override
protected Response parseNetworkResponse(NetworkResponse response) {
        Response 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封装))