nohttp实战

MyApplication.java

package com.htt.baseviews;

import android.app.Application;

import com.htt.album.load.GlideAlbumLoader;
import com.yanzhenjie.album.Album;
import com.yanzhenjie.album.AlbumConfig;
import com.yanzhenjie.nohttp.InitializationConfig;
import com.yanzhenjie.nohttp.NoHttp;
import com.yanzhenjie.nohttp.URLConnectionNetworkExecutor;
import com.yanzhenjie.nohttp.cache.DBCacheStore;
import com.yanzhenjie.nohttp.cookie.DBCookieStore;
import java.util.Locale;

/**
 *程序的Application
 * //https://github.com/yanzhenjie/NoHttp
 */
public class MyApplication extends Application
{
    @Override
    public void onCreate() {
        super.onCreate();
        // 如果你需要自定义配置:
        NoHttp.initialize(InitializationConfig.newBuilder(this)
                // 设置全局连接超时时间,单位毫秒,默认10s。
                .connectionTimeout(30 * 1000)
                // 设置全局服务器响应超时时间,单位毫秒,默认10s。
                .readTimeout(30 * 1000)
                // 配置缓存,默认保存数据库DBCacheStore,保存到SD卡使用DiskCacheStore。
                .cacheStore(
                        new DBCacheStore(this).setEnable(true) // 如果不使用缓存,设置setEnable(false)禁用。
                )
                // 配置Cookie,默认保存数据库DBCookieStore,开发者可以自己实现。
                .cookieStore(
                        new DBCookieStore(this).setEnable(true) // 如果不维护cookie,设置false禁用。
                )
                // 配置网络层,URLConnectionNetworkExecutor,如果想用OkHttp:OkHttpNetworkExecutor。
                .networkExecutor(new URLConnectionNetworkExecutor())
                .build()
        );



        Album.initialize(
                AlbumConfig.newBuilder(this)
                        .setAlbumLoader(new GlideAlbumLoader()) // This is not necessary.
                        .setLocale(Locale.getDefault())
                        .build()
        );
    }
}

BaseActivity.java

package com.htt.baseviews;



/**
 * 程序主要入口
 * authore 惠涛
 */
public class BaseActivity implements INoHttp,UploadNoHttp{

    private Dialog mReponseServerDialog;
    public BaseHttpRequest method;
    
    @Override
    protected void onCreate( Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setStartData();
        
        init();
        
    }
    /**
     * 页面加载数据是的dialog
     * @param title
     * @param message
     */
    public void showProgressDialog(String title, String message)
    {
        if(null != mReponseServerDialog && mReponseServerDialog.isShowing())
        {
            return;
        }
        View mView = getLayoutInflater().inflate(R.layout.progressdialog, null);
        LinearLayout layout = (LinearLayout) mView.findViewById(R.id.dialog_view);// 加载布局
        // progressdialog.xml中的ImageView
        ImageView spaceshipImage = (ImageView) mView.findViewById(R.id.imageProgressDialog);
        TextView tipTextView = (TextView) mView.findViewById(R.id.tipTextView);
        // 加载动画
        Animation hyperspaceJumpAnimation = AnimationUtils.loadAnimation(
                this, R.anim.progress_anim);
        // 使用ImageView显示动画
        spaceshipImage.startAnimation(hyperspaceJumpAnimation);
        tipTextView.setText(message);// 设置加载信息

        mReponseServerDialog =  new Dialog(this,R.style.ProgressRoundTheme);
//		mReponseServerDialog = new ProgressDialog(this);
//		mReponseServerDialog.setTitle(title);
//		mReponseServerDialog.setMessage(message);
        mReponseServerDialog.setContentView(layout, new LinearLayout.LayoutParams(
                ViewGroup.LayoutParams.FILL_PARENT,
                ViewGroup.LayoutParams.FILL_PARENT));// 设置布局
        mReponseServerDialog.setCancelable(false);
        mReponseServerDialog.show();
    }
    public void closeProgressDialog(){
        if(null != mReponseServerDialog && mReponseServerDialog.isShowing())
        {
            mReponseServerDialog.dismiss();
        }
    }

    //  初始化监听
    public void setStartData() {
        method=new BaseHttpRequest();
        method.setINoHttpListener(this);
        method.setUploadHttpListener(this);
    }



    //实现了nohttp String请求的的接口
    @Override
    public void onStart(int what) {
        showProgressDialog(null, null);
    }
    @Override
    public void onSucceed(int what, Response<String> response, BaseListener listener, Class<?> cls) {
        System.out.print(response.toString());
    }

    @Override
    public void onFailed(int what, Response<String> response) {
        Toast.makeText(this,"数据加载失败",Toast.LENGTH_SHORT).show();
//      closeProgressDialog();
    }

    @Override
    public void onFinish(int what) {
        closeProgressDialog();
    }


    //文件加载的接口回调
    @Override
    public void onStartFile(int what) {

    }

    @Override
    public void onCancelFile(int what) {

    }

    @Override
    public void onProgressFile(int what, int progress) {

    }

    @Override
    public void onFinishFile(int what) {

    }

    @Override
    public void onErrorFile(int what, Exception exception) {

    }


   

}

BaseDataActivity.java

package com.htt.baseviews;

import android.os.Bundle;

import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.htt.listener.BaseListener;
import com.htt.model.BaseBean;
import com.yanzhenjie.nohttp.rest.Response;

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

/**
 * Created by seer on 2017/10/26.
 * huitao
 * ,主要是解析数据返回的接口处理
 */
public class BaseDataActivity extends BaseActivity implements BaseListener{
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setData();
    }

    /**
     * 初始化接口的回调
     */
    private void setData() {
        method.setUIresuleListener(this);
    }

    @Override
    public void onSucceed(int what, Response<String> response, BaseListener listener, Class<?> cls) {
        super.onSucceed(what, response,listener,cls);
        BaseBean data=null;
        if (response.responseCode() == 200) {
            String result = response.get();
//          Gson gson = new Gson();
//          Type objectType = type(BaseBean.class, cls);
//          Type type = getType();
//          BaseBean data = gson.fromJson(result, objectType);
//          listener.onDataChanged(what, data);
            try {
                data =fromJsonObject(result, cls);
            } catch (JsonSyntaxException e) {//解析异常,说明是array数组
                data = fromJsonArray(result, cls);
            }finally {
                if(data!=null){
                    listener.onDataChanged(what, data);
                }
            }
//            Type type = getType();
//            //解析对象
//                if (type == String.class) {
//                    BaseBean data = fromJsonObject(result, cls);
//                    listener.onDataChanged(what, data);
//                } else if (type == List.class) {
//                    //list没有指定泛型类型的
//
//                } else if (type == Map.class) {
//                    //map没有指定泛型类型的
//
//                } else if (type instanceof ParameterizedType && ((ParameterizedType) type).getActualTypeArguments().length == 1) {
//                    //List指定泛型类型的
//                    BaseBean data = fromJsonArray(result, cls);
//                    listener.onDataChanged(what, data);
//                } else if (type instanceof ParameterizedType && ((ParameterizedType) type).getActualTypeArguments().length == 2) {
//                    //map指定泛型类型的
//
//                } else {
//                    //其它单个对象类型
//                }
        }

    }
    @Override
    public void onDataChanged(int what, BaseBean bean)
             {
        System.out.print(bean);
    }

    //    /**
//     * 反射接口gson解析
//     * @param raw
//     * @param args
//     * @return
//     */
//    private static ParameterizedType type(final Class raw, final Type... args) {
//        return new ParameterizedType() {
//            public Type getRawType() {
//                return raw;
//            }
//
//            public Type[] getActualTypeArguments() {
//                return args;
//            }
//
//            public Type getOwnerType() {
//                return null;
//            }
//        };
//    }
    //判断返回数据的类型
    public Type getType() {
        ParameterizedType genType = (ParameterizedType) getClass().getGenericSuperclass();

        Type[] actualTypeArguments = ((ParameterizedType) genType).getActualTypeArguments();

        return actualTypeArguments[0];
    }

    public class ParameterizedTypeImpl implements ParameterizedType {
        private final Class raw;
        private final Type[] args;

        public ParameterizedTypeImpl(Class raw, Type[] args) {
            this.raw = raw;
            this.args = args != null ? args : new Type[0];
        }

        @Override
        public Type[] getActualTypeArguments() {
            return args;
        }

        @Override
        public Type getRawType() {
            return raw;
        }

        @Override
        public Type getOwnerType() {
            return null;
        }
    }
    public  <T> BaseBean<T> fromJsonObject(String reader, Class<T> clazz) {
        Type type = new ParameterizedTypeImpl(BaseBean.class, new Class[]{clazz});
        return new Gson().fromJson(reader, type);
    }

    public  <T> BaseBean<List<T>> fromJsonArray(String reader, Class<T> clazz) {
        // 生成List<T> 中的 List<T>
        Type listType = new ParameterizedTypeImpl(List.class, new Class[]{clazz});
        // 根据List<T>生成完整的Result<List<T>>
        Type type = new ParameterizedTypeImpl(BaseBean.class, new Type[]{listType});
        return new Gson().fromJson(reader, type);
    }

}

 

package com.htt.http;

import com.htt.listener.BaseListener;
import com.yanzhenjie.nohttp.rest.Response;

/**
 * Created by seer on 2017/10/25.
 * huitao
 */
public interface INoHttp {
    /**
     * 请求的开始
     * @param what  请求的标识
     */
    void onStart(int what);

    /**
     * 请求成功的方法
     * @param what  请求的标识
     * @param response  响应的结果
     */
    void onSucceed(int what, Response<String> response, BaseListener listener, Class<?> cls);

    /**
     * 请求失败调用这个方法
     * @param what 请求的标识
     * @param response  响应的结果
     */
    void onFailed(int what, Response<String> response);

    /**
     * 请求完成
     * @param what 请求的标识
     */
    void onFinish(int what);
}
package com.htt.http;

import com.htt.listener.BaseListener;
import com.yanzhenjie.nohttp.BasicBinary;
import com.yanzhenjie.nohttp.NoHttp;
import com.yanzhenjie.nohttp.RequestMethod;
import com.yanzhenjie.nohttp.rest.Request;
import com.yanzhenjie.nohttp.rest.RequestQueue;

/**
 * Created by seer on 2017/10/25.
 * huitao
 */
public class NoHttpUtils {
    /**
     * get请求方式
     * @param url
     * @param iNoHttp
     */
    public static void nohttpGet(RequestQueue requestQueue,int what,String url, INoHttp iNoHttp,BaseListener listener,Class<?> cls){

        //得到请求  参数一:url路径 参数二:请求的方式
        Request<String> request = NoHttp.createStringRequest(url, RequestMethod.GET);
        requestQueue.add(what, request,new NohttpCallback(iNoHttp,listener,cls));
    }

    /**
     * nohttp的post请求方式
     * @param request 请求的示例
     * @param iNoHttp  回调的结果
     */
    public static void nohttpPost(RequestQueue requestQueue, int what, Request<String> request, INoHttp iNoHttp, BaseListener listener,Class<?> cls){

        requestQueue.add(what,request,new NohttpCallback(iNoHttp,listener,cls));
    }

    /**
     * nohttp实现单文件上传
     * @param requestQueue
     * @param what
     * @param request
     * @param iNoHttp
     */
    public static void nohttpSingleFile(RequestQueue requestQueue, int what, Request<String> request,UploadNoHttp uploadNoHttp,INoHttp iNoHttp, BasicBinary binary){
        binary.setUploadListener(0, new NoHttpFileCallBack(uploadNoHttp));
        requestQueue.add(what,request,new NohttpCallback(iNoHttp,null,null));
    }
    /**
     * nohttp实现多文件上传
     * @param requestQueue
     * @param what
     * @param request
     * @param iNoHttp
     */
    public static void nohttpMoreFile(RequestQueue requestQueue,int what, Request<String> request, INoHttp iNoHttp){

        requestQueue.add(what,request,new NohttpCallback(iNoHttp,null,null));
    }
}
package com.htt.http;

/**
 * Created by seer on 2017/10/25.
 */
public interface UploadNoHttp {
    /**
     *开始
     * @param what
     */
    void onStartFile(int what);

    /**
     *取消
     * @param what
     */
    void onCancelFile(int what);

    /**
     *加载进度条
     * @param what
     * @param progress
     */
    void onProgressFile(int what, int progress);

    /**
     *完成
     * @param what
     */
    void onFinishFile(int what);

    /**
     *发生错误
     * @param what
     * @param exception
     */
    void onErrorFile(int what, Exception exception);

}
package com.htt.http;

import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.htt.listener.BaseListener;
import com.htt.model.BaseBean;
import com.yanzhenjie.nohttp.rest.OnResponseListener;
import com.yanzhenjie.nohttp.rest.Response;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.List;

/**
 * Created by seer on 2017/10/25.
 * huitao
 */
public class NohttpCallback implements OnResponseListener<String> {
    /**
     * 初始化INoHttp接口
     */
    private INoHttp iNoHttp;
    private BaseListener listener;
    Class<?> cls;


    /**
     * 有参构造函数
     *
     * @param iNoHttp
     */
    public NohttpCallback(INoHttp iNoHttp, BaseListener listener, Class<?> cls) {
        this.iNoHttp = iNoHttp;
        this.listener = listener;
        this.cls = cls;
    }

    /**
     * 请求开始
     *
     * @param what
     */
    @Override
    public void onStart(int what) {
        iNoHttp.onStart(what);
    }

    /**
     * 请求成功
     * 做数据解析返回结果
     *
     * @param what
     * @param response
     */
    @Override
    public void onSucceed(int what, Response<String> response) {
            iNoHttp.onSucceed(what, response,listener,cls);
        }
    /**
     * 请求失败
     * @param what
     * @param response
     */
    @Override
    public void onFailed(int what, Response<String> response)
    {
        iNoHttp.onFailed(what,response);
    }

    /**
     * 请求完成
     * @param what
     */
    @Override
    public void onFinish(int what) {
        iNoHttp.onFinish(what);
    }



}
package com.htt.http;

import com.yanzhenjie.nohttp.OnUploadListener;

/**
 * Created by seer on 2017/10/25.
 * huitao
 */
public class NoHttpFileCallBack implements OnUploadListener
{
    private UploadNoHttp uploadNoHttp;
    /**
     *
     * @param uploadNoHttp
     */
    public NoHttpFileCallBack(UploadNoHttp uploadNoHttp){
       this.uploadNoHttp=uploadNoHttp;
    }
    @Override
    public void onStart(int what) {
        uploadNoHttp.onStartFile(what);
    }

    @Override
    public void onCancel(int what) {
        uploadNoHttp.onCancelFile(what);
    }

    @Override
    public void onProgress(int what, int progress) {
        uploadNoHttp.onProgressFile(what,progress);
    }

    @Override
    public void onFinish(int what) {
        uploadNoHttp.onFinishFile(what);

    }

    @Override
    public void onError(int what, Exception exception) {
        uploadNoHttp.onErrorFile(what,exception);

    }
}

BaseListener.java

package com.htt.listener;

import com.htt.model.BaseBean;

/**
 * 回调接口获取返回的数据
 */
public interface BaseListener {
    void onDataChanged(int what, BaseBean bean);
}
 <!-- nohttp的网络权限 -->
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
    <uses-permission android:name="android.permission.CAMERA"/>
    <uses-permission android:name="android.permission.RECORD_AUDIO"/>

我自己配置的网络框架,绝大多数代码都在里面!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值