nohttp

dependencies

compile 'com.yolanda.nohttp:nohttp:1.0.4'

初始化

  • application
public class TestApp extends Application {
    @Override
     public void onCreate() {
        super.onCreate();
        NoHttp.initialize(this);
    }
}
  • activity
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);
        Logger.setDebug(true);  //打开测试,可以查看,req resp  内容
        requestQueue = NoHttp.newRequestQueue(3);
        // 或者传一个并发值,允许三个请求同时并发

    }
  • 权限
    
    
    
    
    

get请求

@OnClick(R.id.bt_test_get)
public void test_get() {
    Request request = NoHttp.createStringRequest("http://ip.taobao.com/service/getIpInfo.php", RequestMethod.GET);
    request.add("ip", "180.111.32.190");
    request.addHeader("a", "b");
    request.setCacheMode(CacheMode.ONLY_REQUEST_NETWORK);
    request.setUserAgent(request.getUserAgent()+" android1234");
    // 发起请求
    requestQueue.add(0, request, this);
}

下载图片

@OnClick(R.id.bt_test_image)
public void get_image(){
    Request request = NoHttp.createImageRequest("https://www.baidu.com/img/baidu_jgylogo3.gif");
    request.setCacheMode(CacheMode.ONLY_READ_CACHE);
    requestQueue.add(1, request, new OnResponseListener() {
        @Override
        public void onStart(int what) {
        }
        @Override
        public void onSucceed(int what, Response response) {
            iv.setImageBitmap(response.get());
        }
        @Override
        public void onFailed(int what, String url, Object tag, Exception exception, int responseCode, long networkMillis) {
        }
        @Override
        public void onFinish(int what) {
        }
    });
}

注意:

  • 在activity 页面发起的请求,需要在页面关闭时,取消.
private Request request;
    @Override
    protected void onDestroy() {
        super.onDestroy();
        if(request!=null)
            request.cancel();
    }

可以在baseActivity里面,提供一个队列,每次调用请求,添加到队列,页面关掉时候,遍历取消请求.

  • Logger.setDebug(true); //打开测试,可以查看,req resp 内容

缓存模式

        CacheMode.DEFAULT;  //默认
        CacheMode.NONE_CACHE_REQUEST_NETWORK;  //没有缓存,走网络
        CacheMode.ONLY_READ_CACHE;//仅缓存
        CacheMode.ONLY_REQUEST_NETWORK;//仅网络
        CacheMode.REQUEST_NETWORK_FAILED_READ_CACHE;//网络失败下,走缓存

资料链接:http://blog.csdn.net/yanzhenjie1003/article/details/50679905

你可能感兴趣的:(nohttp)