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"/>

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

NoHttp 是专门做Android网络请求与下载的框架。支持HTTP/HTTPS,自动维持Cookie,异步/同步请求,大文件/多文件上传,文件下载;支持304缓存,302/303重定向,支持代理服务器。NoHttp特性:支持HTTP/HTTPS,自动维持Cookie,异步/同步请求,大文件/多文件上传,文件下载,上传下载均有进度。支持304缓存,自定义缓存,302/303重定向,支持代理服务器访问地址(如: Google)。NoHttp是队列,自动为请求排队,可以取消指定请求, 可以取消队列所有请求,亦可以停止队列。支持请求String、Bitmap、Json、JavaBean,可自定义扩展请求类型。Request对象包涵参数、文件、请求头等;Response对象包涵响应内容,响应头等信息,Cookie。使用Gradle构建时添加依赖:// 引用最新版 compile 'com.yolanda.nohttp:nohttp: ' // 或则引用指定版本 compile 'com.yolanda.nohttp:nohttp:1.0.0'一. 请求1.请求String数据// 请求对象 Request request = NoHttp.createStringRequest(url, requestMethod); //添加请求头 request.addHeader("AppVersioin", "2.0"); // 添加请求参数 request.add("userName", "yolanda"); //上传文件 request.add("file", new FileBinary(file)); ...2.请求Json数据// JsonObject Request request = NoHttp.createJsonObjectRequest(url, reqeustMethod); queue.add(what, request, responseListener); … // JsonArray Request request = NoHttp.createJsonArrayRequest(url, reqeustMethod); queue.add(what, request, responseListener);3. 请求Bitmap数据Request request = NoHttp.createImageRequest(url, requestMethod); ...4. 取消请求取消单个请求Request request = NoHttp.createStringRequest(url); ... request.cancel();从队列中取消指定的请求Request request = NoHttp.createStringRequest(url); request.setCancelSign(sign); … queue.cancelBySign(sign);取消队列中所有请求queue.cancelAll();停止队列RequestQueue queue = NoHttp.newRequestQueue(); ... queue.stop();5. 同步请求// 在当前线程发起请求,在线程这么使用 Request request = NoHttp.createStringRequest(url); Response response = NoHttp.startRequestSync(request); if (response.isSucceed()) {     // 请求成功 } else {     // 请求失败 }二. 缓存1. Http标准协议的缓存,比如响应码是304时现在很多公司使用了RESTFUL风格来写Http API,所以这个是必须有的。Request request = NoHttp.createJsonObjectRequest(url); // NoHttp本身是RESTFUL风格的标准Http协议,所以这里不用设置或者设置为DEFAULT request.setCacheMode(CacheMode.DEFAULT); ...2. 当请求服务器失败的时候,读取缓存Request request = NoHttp.createJsonObjectRequest(url); // 非标准Http协议,改变缓存模式为REQUEST_FAILED_READ_CACHE request.setCacheMode(CacheMode.REQUEST_FAILED_READ_CACHE); ...3. 如果发现有缓存直接成功,没有缓存才请求服务器我们知道ImageLoader的核心除了内存优化外,剩下一个就是发现把内地有图片则直接使用,没有则请求服务器,所以NoHttp这一点非常使用做一个ImageLoader。Request request = NoHttp.createJsonObjectRequest(url); // 非标准Http协议,改变缓存模式为IF_NONE_CACHE_REQUEST request.setCacheMode(CacheMode.IF_NONE_CACHE_REQUEST); ...请求图片,缓存图片。// 如果没有缓存才去请求服务器,否则使用缓存,缓存图片演示 Request request = NoHttp.createImageRequest(imageUrl); request.setCacheMode(CacheMode.IF_NONE_CACHE_REQUEST); ...4. 仅仅读取缓存Request request = NoHttp.createJsonObjectRequest(url); // 非标准Http协议,改变缓存模式为ONLY_READ_CACHE request.setCacheMode(CacheMode.ONLY_READ_CACHE); ...注意:缓存不管是String、Json、图片还是任何请求都可以被NoHttp缓存二、响应OnResponseListener responseListener = new OnResponseListener() {     @Override     public void onStart(int what) {         // 请求开始时,可以显示一个Dialog     }     @Override     public void onFinish(int what) {         // 请求接受时,关闭Dialog     }     @Override     public void onSucceed(int what, Response response) {         // 接受请求结果         String result = response.get();         // Bitmap imageHead = response.get(); // 如果是bitmap类型,都是同样的用法     }     @Override     public void onFailed(int what, String url, Object tag, Exception exception, ...) {         // 请求失败或者发生异常         // 这里根据exception处理不同的错误,比如超时、网络不好等     } };三. 自定义请求类型: FastJsonRequest1.定义请求对象public class FastJsonRequest extends RestRequestor { public FastJsonRequest(String url) {     super(url); } public FastJsonRequest(String url, RequestMethod requestMethod) {     super(url, requestMethod); } @Override public JSONObject parseResponse(String url, Headers headers, byte[] responseBody) {     String result = StringRequest.parseResponseString(url, headers, responseBody);     JSONObject jsonObject = null;     if (!TextUtils.isEmpty(result)) {         jsonObject = JSON.parseObject(result);     } else {         // 这里默认的错误可以定义为你们自己的数据格式         jsonObject = JSON.toJSON("{}");     }     return jsonObject; } @Override public String getAccept() {     // 告诉服务器你接受什么类型的数据, 会添加到请求头的Accept中     return "application/json;q=1"; } }2.使用自定义请求-和NoHttp默认请求没有区别Request mRequest = new FastJsonRequest(url, requestMethod); queue.add(what, mRequest, responseListener);五. 下载文件发起下载请求//下载文件 downloadRequest = NoHttp.createDownloadRequest(url, fielDir, fileName, true, false); // what 区分下载 // downloadRequest 下载请求对象 // downloadListener 下载监听 CallServer.getDownloadInstance().add(0, downloadRequest, downloadListener);暂停或者停止下载downloadRequest.cancel();监听下载过程private DownloadListener downloadListener = new DownloadListener() {     @Override     public void onStart(int what, boolean resume, long preLenght, Headers header, long count) {     }     @Override     public void onProgress(int what, int progress, long downCount) {         // 更新下载进度     }     @Override     public void onFinish(int what, String filePath) {     }     @Override     public void onDownloadError(int what, StatusCode code, CharSequence message) {     }     @Override     public void onCancel(int what) {     } }; 标签:NoHttp
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值