奶牛刀

Retrofit自定义Converter数据异常处理攻略

2017-09-30  本文已影响0人  百分之百胜率后羿

开发中客户端时常与服务端打交道,客户端请求参数到服务端,服务端返回响应数据到客户端,开发中用的比较多的就是Json数据传递,从请求到响应的步骤一般是约定数据格式,响应数据进行关系映射,然后对错误数据进行异常处理。

数据格式

一个比较良好的的响应数据应该具备响应码、数据状态描述、具体的响应数据

{
"message": "正常",
"responsecode": 0,
"results": {
"list": [
{
"desc": "HorizontalPicker view 支持文本和icon",
"id": "58b7c6da421aa90f131785f0",
"type": "Android",
"who": "Jason"
},
{
"desc": "VirtualLayout是一个针对RecyclerView的LayoutManager扩展",
"id": "58bb931a421aa90efc4fb65b",
"type": "Android",
"who": "Jason"
}
],
"total": 2
}
}

responsecode

responsecode为服务器自定义的响应码

<table>
<tr>
<td>0</td>
<td>成功</td>
</tr>
<tr>
<td>1</td>
<td>该用户不存在</td>
</tr>
<tr>
<td>2</td>
<td>充值失败</td>
</tr>
<tr>
<td>3</td>
<td>非法请求</td>
</tr>
<tr>
<td>4</td>
<td>服务器繁忙</td>
</tr>
</table>

message

服务端返回数据的状态描述,客户端可以根据需要对操作信息进行显示,当然客户端也可以自定义状态的描述。

results

服务器返回的具体数据,客户端需要对响应数据进行实体类的映射

返回数据映射成实体类

一般来讲,客户端与服务端之间的数据通信大部分是以Json格式进行,我们根据服务端返回的数据来抽象出我们的实体类

public class HttpResult<T> {
    private int responsecode;
    private String message;
    private T results;
    public int getResponsecode() {
        return responsecode;
    }
    public void setResponsecode(int responsecode) {
        this.responsecode = responsecode;
    }
    public String getMessage() {
        return message;
    }
    public void setMessage(String message) {
        this.message = message;
    }
    public T getResults() {
        return results;
    }
    public void setResults(T results) {
        this.results = results;
    }
}

HttpResult类为所有数据模型的基类,使用泛型results可以保证接收不同的实体模型。

下面定义具体数据的实体模型:

public class ArticleList {
    private int total;
    private List<Article> list;
    public int getTotal() {
        return total;
    }
    public void setTotal(int total) {
        this.total = total;
    }
    public List<Article> getList() {
        return list;
    }
    public void setList(List<Article> list) {
        this.list = list;
    }
}
public class Article {
    private String id;
    private String type;
    private String who;
    private String desc;
    public String getId() {
        return id;
    }
    public void setId(String id) {
        this.id = id;
    }
    public String getType() {
        return type;
    }
    public void setType(String type) {
        this.type = type;
    }
    public String getWho() {
        return who;
    }
    public void setWho(String who) {
        this.who = who;
    }
    public String getDesc() {
        return desc;
    }
    public void setDesc(String desc) {
        this.desc = desc;
    }
}

映射实体类定义完毕之后,我们使用retrofit定义数据请求接口:

@POST("android/article/list")
Call<HttpResult<ArticleList>> getArticleList(@Body ArticlePost post);

上述接口参数ArticlePost为自定义请求类,里面包含两个字段page(请求页数)和rowcount(请求行数)

要想让我们的实体类与Json之间可以自动转换,我们还需要为retrofit配置converter:

  Retrofit.Builder builder = new Retrofit.Builder()
                .baseUrl(baseUrl)
                .client(ClientFactory.getInstance().getOkHttpClient()
                .addConverterFactory(GsonConverterFactory.create());
  return builder.build().create(clazz);

添加gson转换器之后,我们的请求实体类可以转换为json数据,响应数据可以自动转换为实体类。

接下来再看一下具体的调用

ApiFactory.getArticleApi().getArticleList(articlePost).enqueue(new Callback<HttpResult<ArticleList>>() {
            @Override
            public void onResponse(Call<HttpResult<ArticleList>> call, Response<HttpResult<ArticleList>> response) {
                HttpResult<ArticleList> body = response.body();
                int code = body.getResponsecode();
                if (code == 0) {
                    //正常响应
                } else {//响应异常
                    switch (code) {
                        case 1:
                            break;
                        case 2:
                            break;
                        case 3:
                            break;
                        case 4:
                            break;
                                  }
                      }
            }
            @Override
            public void onFailure(Call<HttpResult<ArticleList>> call, Throwable t) {

            }
        });

引入RxJava的使用

retrofit框架支持对RxJava的引入,引入RxJava之后可以让我们更好的进行线程控制以及数据处理。

RxJava的引入

想要使用RxJava,在gradle文件中添加依赖即可:

compile 'io.reactivex:rxjava:1.1.0'
compile 'io.reactivex:rxandroid:1.1.0'

另外还需要引入RxJava适配器的依赖:

compile 'com.squareup.retrofit2:adapter-rxjava:2.1.0'
然后在retrofit中添加适配器:

 Retrofit.Builder builder = new Retrofit.Builder()
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                return builder.build().create(clazz);

引入之后,我们就可以把之前接口的返回定义为Observable接口:如下:

@POST("android/article/list")
Observable<HttpResult<ArticleList>> getArticleList(@Body ArticlePost post);

引入RxJava之后数据接口的使用

ApiFactory.getArticleApi().getArticleList(articlePost)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<HttpResult<ArticleList>>() {
                    @Override
                    public void onNext(HttpResult<ArticleList> result) {
                        int code = body.getResponsecode();
                        if (code == 0) {
                            //正常响应
                            ArticleList list=result.getResults;
                        } else {//响应异常
                            switch (code) {
                                case 1:
                                    break;
                                case 2:
                                    break;
                                case 3:
                                    break;
                                case 4:
                                    break;
                                          }
                              }
                    }
                    @Override
                    public void onError(Throwable e) {
                       
                    }
                
                    @Override
                    public void onCompleted() {
                
                    }
                });

这样我们就初步的把异常处理完了,一般来讲我们想在onNext回调中只处理正常的业务逻辑,而现在错误的业务逻辑也包含在了onNext中,这并不是我们想要的,我们的目的是在onError中处理错误逻辑。

如果返回的数据转换为实体类的时候发现是错误的响应码直接能够抛出异常,并让onError直接去捕获异常就能够达到我们的预期,说到实体类的转换我们很自然的就想到了之前添加GsonConverter,我们来看一下GsonConverterFactory的源码实现:

public final class GsonConverterFactory extends Converter.Factory {
  public static GsonConverterFactory create() {
    return create(new Gson());
  }

  public static GsonConverterFactory create(Gson gson) {
    return new GsonConverterFactory(gson);
  }

  private final Gson gson;

  private GsonConverterFactory(Gson gson) {
    if (gson == null) throw new NullPointerException("gson == null");
    this.gson = gson;
  }

  @Override
  public Converter<ResponseBody, ?> responseBodyConverter(Type type, Annotation[] annotations,
      Retrofit retrofit) {
    TypeAdapter<?> adapter = gson.getAdapter(TypeToken.get(type));
    return new GsonResponseBodyConverter<>(adapter);
  }

  @Override
  public Converter<?, RequestBody> requestBodyConverter(Type type,
      Annotation[] parameterAnnotations, Annotation[] methodAnnotations, Retrofit retrofit) {
    TypeAdapter<?> adapter = gson.getAdapter(TypeToken.get(type));
    return new GsonRequestBodyConverter<>(gson, adapter);
  }
}

其中有两个方法:responseBodyConverterrequestBodyConverter,其功能就是创建响应体跟请求体转换器。
我们再分别追踪一下GsonResponseBodyConverterGsonRequestBodyConverter的源码:

GsonResponseBodyConverter.java

final class GsonResponseBodyConverter<T> implements Converter<ResponseBody, T> {
  private final TypeAdapter<T> adapter;

  GsonResponseBodyConverter(TypeAdapter<T> adapter) {
    this.adapter = adapter;
  }

  @Override public T convert(ResponseBody value) throws IOException {
    try {
      return adapter.fromJson(value.charStream());
    } finally {
      value.close();
    }
  }
}

实现比较简单,convert方法完成了Json数据到实体类的映射。

GsonRequestBodyConverter.java

final class GsonRequestBodyConverter<T> implements Converter<T, RequestBody> {
  private static final MediaType MEDIA_TYPE = MediaType.parse("application/json; charset=UTF-8");
  private static final Charset UTF_8 = Charset.forName("UTF-8");

  private final Gson gson;
  private final TypeAdapter<T> adapter;

  GsonRequestBodyConverter(Gson gson, TypeAdapter<T> adapter) {
    this.gson = gson;
    this.adapter = adapter;
  }

  @Override public RequestBody convert(T value) throws IOException {
    Buffer buffer = new Buffer();
    Writer writer = new OutputStreamWriter(buffer.outputStream(), UTF_8);
    JsonWriter jsonWriter = gson.newJsonWriter(writer);
    adapter.write(jsonWriter, value);
    jsonWriter.close();
    return RequestBody.create(MEDIA_TYPE, buffer.readByteString());
  }
}

convert方法完成了实体类到Json数据的转换

使用自定义Converter配合RxJava进行异常的统一处理

我们根据源码提供的转换器来创建自己的Converter,然后在响应转换时根据响应码去抛出异常让onError去捕获。
首先我们来创建自己的响应体转换器。

public class CheckGsonResponseBodyConverter<T> implements Converter<ResponseBody, T> {
    private final TypeAdapter<T> adapter;
    private final Gson mGson;
    private static final Charset UTF_8 = Charset.forName("UTF-8");

    CheckGsonResponseBodyConverter(TypeAdapter<T> adapter) {
        this.mGson = new Gson();
        this.adapter = adapter;
    }

    @Override
    public T convert(ResponseBody value) throws IOException {
        String response = value.string();
        HttpResult result = mGson.fromJson(response, HttpResult.class);
        int responseCode = result.getResponsecode();
        //如果响应码不为正常响应我们就抛出一个自定义的异常,onError方法回去捕获这个异常
        if (!responseCode == 0) {
            value.close();
            throw new ApiException(responseCode, ApiError.getErrorMessage(responseCode));
        }
        MediaType type=value.contentType();
        Charset charset=type!=null?type.charset(UTF_8):UTF_8;
        InputStream is = new ByteArrayInputStream(response.getBytes());
        InputStreamReader reader = new InputStreamReader(is,charset);
        JsonReader jsonReader = mGson.newJsonReader(reader);
        try {
            return adapter.read(jsonReader);
        } finally {
            value.close();
        }
    }
}

接着我们创建自己的请求体转换器:

public class CheckGsonRequestBodyConverter<T> implements Converter<T, RequestBody> {
    private static final MediaType MEDIA_TYPE = MediaType.parse("application/json; charset=UTF-8");
    private static final Charset UTF_8 = Charset.forName("UTF-8");

    private final Gson gson;
    private final TypeAdapter<T> adapter;

    CheckGsonRequestBodyConverter(Gson gson, TypeAdapter<T> adapter) {
        this.gson = gson;
        this.adapter = adapter;
    }

    @Override
    public RequestBody convert(T value) throws IOException {
        Buffer buffer = new Buffer();
        Writer writer = new OutputStreamWriter(buffer.outputStream(), UTF_8);
        JsonWriter jsonWriter = gson.newJsonWriter(writer);
        adapter.write(jsonWriter, value);
        jsonWriter.close();
        return RequestBody.create(MEDIA_TYPE, buffer.readByteString());
    }
}

最后我们还需要创建一个转换器工厂:

public class CheckGsonConverterFactory extends Converter.Factory {

    public static CheckGsonConverterFactory create() {
        return create(new Gson());
    }


    public static CheckGsonConverterFactory create(Gson gson) {
        return new CheckGsonConverterFactory(gson);
    }

    private final Gson gson;

    private CheckGsonConverterFactory(Gson gson) {
        if (gson == null) throw new NullPointerException("gson == null");
        this.gson = gson;
    }

    @Override
    public Converter<ResponseBody, ?> responseBodyConverter(Type type, Annotation[] annotations,
                                                            Retrofit retrofit) {
        TypeAdapter<?> adapter = gson.getAdapter(TypeToken.get(type));
        //返回自定义的响应体转换器
        return new CheckGsonResponseBodyConverter<>(adapter);
    }

    @Override
    public Converter<?, RequestBody> requestBodyConverter(Type type,
                                                          Annotation[] parameterAnnotations, Annotation[] methodAnnotations, Retrofit retrofit) {
        TypeAdapter<?> adapter = gson.getAdapter(TypeToken.get(type));
        //返回自定义的请求转换器
        return new CheckGsonRequestBodyConverter<>(gson, adapter);
    }
}

到现在自定义的Converter已经完成,我们在retrofit中配置一下:

Retrofit.Builder builder = new Retrofit.Builder()
                .baseUrl(baseUrl)
                .client(ClientFactory.getInstance().getOkHttpClient())
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .addConverterFactory(CheckGsonConverterFactory.create());
        return builder.build().create(clazz);

这时我们调用数据接口时代码变为:

ApiFactory.getArticleApi().getArticleList(articlePost)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<HttpResult<ArticleList>>() {
                    @Override
                    public void onNext(HttpResult<ArticleList> result) {
                            //正常响应
                            ArticleList list=result.getResults;
                    }
                    @Override
                    public void onError(Throwable e) {
                        if (e instanceof HttpException || e instanceof IOException)      {
                        //异常处理
                        } else {
                        //处理api异常
                        ApiException apiException=(ApiException)e;
                        handleApiError(context, e);
                        }
                    }
                
                    @Override
                    public void onCompleted() {
                
                    }
                });

这样我们通过自定义Converter的方式将异常响应码的逻辑全部交给了onError去处理,而在onNext中我们只关注正确的逻辑,这时我们就完成了对数据异常的统一处理。

下面附上源码,Demo中暂时没有合适的数据接口可以使用,只看实现思路即可。

上一篇下一篇

猜你喜欢

热点阅读