基於okHttpUtils網絡請求的基類抽取升級版

二次封裝的功能

1,網絡的get請求
2,xml數據解析
3,網絡的post請求
4,支持請求頭的添加
5,支持post文件上傳,類似於表單

注意事項

post請求上傳文件,因爲不知道文件的具體的個數
    1,需要先獲取一個泛型爲<String,File>的Map集合
    2,在okHttpUtils中間,遍歷集合,並添加文件

代碼的實現

package com.example.guixin.oschina.base;

import com.example.guixin.oschina.util.XmlUtils;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.builder.PostFormBuilder;
import com.zhy.http.okhttp.callback.StringCallback;

import java.io.File;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.Map;

import okhttp3.Call;

/**
 * Author:      歸零
 * Date:        2017/3/4 9:31
 * Email:       4994766@qq.com
 * Description:1,get請求 2,xml數據的解析 3,post請求 4,請求頭的添加
 * <p>
 * 需要改變的地方
 * 1,NewsPagerProtocol.Callback  改爲 BaseProtocol
 * 2,參數不確定,提供一個方法 子類必須實現
 * 3,Url不確定,提供一個方法,子類必須實現
 * 4,泛型的改變
 * 1,將要改變的類型,變爲泛型
 * 1,使用泛型後要在類或者接口中聲明泛型
 * 2,在類或者接口使用的地址,添加泛型
 * 3,在使用的類或者接口聲明泛型
 * 2,
 */
public abstract class BaseProtocol<RESTYPE> {


    protected int mCurrentPageIndex;

    public void setCurrentPageIndex(int currentPageIndex) {

        mCurrentPageIndex = currentPageIndex;
    }


    public void loadGetData(final BaseProtocol.Callback<RESTYPE> callback) {
        //決定請求的網絡地址
        String baseUrl = getUrl();
        //http://www.oschina.net/action/api/news_list?pageIndex=0&catalog=1&pageSize=20
        //網絡請求
        OkHttpUtils
                .get()
                .url(baseUrl)
                .headers(getHeaderMap())
                .params(getParamsMap())
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        //因爲返回失敗處理的請求不一樣,所以不處理,交給調用的方法處理
                        callback.onError(call, e, id);
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        //基類裏面通過一定的方式獲取子類傳遞的類型
                        //請求成功,將字符串轉爲javaBean,並獲取裏面的泛型爲News的集合
                        Type type = BaseProtocol.this.getClass().getGenericSuperclass();
                        ParameterizedType parameterizedType = (ParameterizedType) type;
                        Type[] actualTypeArguments = parameterizedType.getActualTypeArguments();
                        Type typeArgument = actualTypeArguments[0];
                        RESTYPE restype = (RESTYPE) XmlUtils.toBean((Class) typeArgument, response.getBytes());
                        //將轉換後的數據通過接口回調,返回給調用方法的
                        callback.onResponse(restype, id);
                    }
                });
    }


    public void loadPostData(final BaseProtocol.Callback<RESTYPE> callback) {
        //決定請求的網絡地址
        String newsUrl = getUrl();

        //網絡請求
        PostFormBuilder postFormBuilder = OkHttpUtils
                .post()
                .url(newsUrl);
        //獲取上傳的文件
        Map<String, File> postFiles = getFilesMap();
        if(postFiles !=null) {
            for (Map.Entry<String, File> info : postFiles.entrySet()) {
                postFormBuilder.addFile(info.getKey(), info.getValue().getName(), info.getValue());
            }
        }

        postFormBuilder.headers(getHeaderMap())
                .params(getParamsMap())
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        //因爲返回失敗處理的請求不一樣,所以不處理,交給調用的方法處理
                        callback.onError(call, e, id);
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        //基類裏面通過一定的方式獲取子類傳遞的類型
                        //請求成功,將字符串轉爲javaBean,並獲取裏面的泛型爲News的集合
                        Type type = BaseProtocol.this.getClass().getGenericSuperclass();
                        ParameterizedType parameterizedType = (ParameterizedType) type;
                        Type[] actualTypeArguments = parameterizedType.getActualTypeArguments();
                        Type typeArgument = actualTypeArguments[0];
                        RESTYPE restype = (RESTYPE) XmlUtils.toBean((Class) typeArgument, response.getBytes());
                        //將轉換後的數據通過接口回調,返回給調用方法的
                        callback.onResponse(restype, id);
                    }
                });
    }




    /**
     * 決定請求的url
     * 在BaseProtocol中不知道具體的實現 交給子類
     * 子類必須實現,定義成爲抽象方法
     *
     * @return
     */
    protected abstract String getUrl();

    /**
     * 決定請求的參數
     * 在BaseProtocol中不知道具體的實現 交給子類實現
     * 子類必須實現 定義成抽象方法
     *
     * @return
     */
    protected HashMap<String, String> getParamsMap() {
        return null;
    }

    ;


    /**
     * 決定請求頭參數
     * 在BaseProtocol中不知道具體的實現 交給子類實現
     * 子類選擇性實現
     *
     * @return
     */
    protected Map<String, String> getHeaderMap() {
        return null;
    }


    /**
     * post實現上傳文件
     * 在BaseProtocol中不知道具體的實現 交給子類實現
     * 子類選擇性實現
     *
     * @return
     */
    protected Map<String, File> getFilesMap() {
        return null;
    }


    public interface Callback<RESTYPE> {

        void onError(Call call, Exception e, int id);

        void onResponse(RESTYPE restype, int id);
    }
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章