com.lzy.demo.supercache.NewsCallback.java Source code

Java tutorial

Introduction

Here is the source code for com.lzy.demo.supercache.NewsCallback.java

Source

/*
 * Copyright 2016 jeasonlzy(?)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.lzy.demo.supercache;

import com.google.gson.stream.JsonReader;
import com.lzy.demo.model.GankResponse;
import com.lzy.demo.utils.Convert;
import com.lzy.okgo.callback.AbsCallback;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

import okhttp3.Response;

/**
 * ================================================
 *     jeasonlzy?Github?https://github.com/jeasonlzy
 *     1.0
 * 16/9/1
 * ??    
 * ?
 * ================================================
 */
public abstract class NewsCallback<T> extends AbsCallback<T> {

    /**
     * ??? http://gank.io/api/data/Android/10/1 ??
     * ,?????,??,?
     */
    @Override
    public T convertResponse(Response response) throws Throwable {
        //???,
        Type genType = getClass().getGenericSuperclass();
        Type[] params = ((ParameterizedType) genType).getActualTypeArguments();
        Type type = params[0];
        if (!(type instanceof ParameterizedType))
            throw new IllegalStateException("?");

        JsonReader jsonReader = new JsonReader(response.body().charStream());
        Type rawType = ((ParameterizedType) type).getRawType();
        if (rawType == GankResponse.class) {
            GankResponse gankResponse = Convert.fromJson(jsonReader, type);
            if (!gankResponse.error) {
                response.close();
                //noinspection unchecked
                return (T) gankResponse;
            } else {
                response.close();
                throw new IllegalStateException("??");
            }
        } else {
            response.close();
            throw new IllegalStateException("?!");
        }
    }
}