Android联网第三方框架NoHttp

1.如果仅仅使用HttpURLConnection作为网络层,在app的gralde中添加以下依赖即可:
1)引用最新版
compile 'com.yolanda.nohttp:nohttp:+'
2)引用指定版本
compile 'com.yolanda.nohttp:nohttp:1.1.0'
2.如果要使用OkHttp作为网络层,请再依赖(注意两个lib的版本需要一致):
compile 'com.yanzhenjie.nohttp:okhttp:1.1.0'
注意:
不论使用基于HttpURLConnection还是OkHttp的版本,NoHttp的使用方法都不会变,这是NoHttp的优点之一。
在依赖中注意写

 implementation 'com.yolanda.nohttp:nohttp:+'
    implementation 'com.yanzhenjie.nohttp:okhttp:+'

就不要写本地依赖jar包他了

 implementation files('libs/okhttp-3.8.0.jar')
    implementation files('libs/okio-1.13.0.jar')

使用

先依赖

compile 'com.yolanda.nohttp:nohttp:+'
    compile 'com.yanzhenjie.nohttp:okhttp:1.1.0'

然后使用

package com.example.administrator.myapplication;

import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.yanzhenjie.nohttp.Headers;
import com.yanzhenjie.nohttp.NoHttp;
import com.yanzhenjie.nohttp.RequestMethod;
import com.yanzhenjie.nohttp.download.DownloadListener;
import com.yanzhenjie.nohttp.download.DownloadQueue;
import com.yanzhenjie.nohttp.download.DownloadRequest;
import com.yanzhenjie.nohttp.rest.CacheMode;
import com.yanzhenjie.nohttp.rest.OnResponseListener;
import com.yanzhenjie.nohttp.rest.Request;
import com.yanzhenjie.nohttp.rest.RequestQueue;
import com.yanzhenjie.nohttp.rest.Response;

import org.json.JSONObject;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class Main3Activity extends AppCompatActivity {

    @BindView(R.id.bu1)
    Button mBu1;
    @BindView(R.id.bu2)
    Button mBu2;
    @BindView(R.id.bu3)
    Button mBu3;
    @BindView(R.id.tx)
    TextView mTx;
    @BindView(R.id.im)
    ImageView mIm;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main3);
        setTitle("Nohttp");
        ButterKnife.bind(this);
        NoHttp.initialize(this);//初始化(可以在Application中进行)
    }

    @OnClick({R.id.bu1, R.id.bu2, R.id.bu3})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.bu1:
                getDataByNoGet();
                break;
            case R.id.bu2:
                getDataByNoPost();
                break;
            case R.id.bu3:
                downloadByNo();
                break;
        }
    }

    private void downloadByNo() {
        String url = "http://p2.so.qhimgs1.com/bdr/200_200_/t012e2b8523a8f88682.jpg";
        String path = Environment.getExternalStorageDirectory().toString();//获取SD卡地址
//        在下载后删除文件,或代表下载是相同的
//                *完成,不处理网络。(下载原有的)
        DownloadRequest downloadRequest = NoHttp.createDownloadRequest(url, path, true);
        DownloadQueue downloadQueue = NoHttp.newDownloadQueue();
        downloadQueue.add(0, downloadRequest, new DownloadListener() {
            @Override
            public void onDownloadError(int what, Exception exception) {

            }

            @Override
            public void onStart(int what, boolean isResume, long rangeSize, Headers responseHeaders, long allCount) {

            }

            @Override
            public void onProgress(int what, int progress, long fileCount, long speed) {
                mTx.setText(progress+"%");
            }

            @Override
            public void onFinish(int what, String filePath) {
                Log.d("data","文件地址:"+filePath);
                mIm.setImageBitmap(BitmapFactory.decodeFile(filePath));
            }

            @Override
            public void onCancel(int what) {

            }
        });


    }

    private void getDataByNoPost() {
        String url = "http://v.juhe.cn/joke/randJoke.php";
        Request jsonArrayRequest = NoHttp.createJsonObjectRequest(url,
                RequestMethod.POST);
        jsonArrayRequest.add("key","cef62c58401d7bfa7d4f6daab78a8d68");
        //设置缓存模式(缓存请求)
        jsonArrayRequest.setCacheMode(CacheMode.REQUEST_NETWORK_FAILED_READ_CACHE);
        RequestQueue requestQueue = NoHttp.newRequestQueue();
        requestQueue.add(1, jsonArrayRequest, new OnResponseListener() {
            @Override
            public void onStart(int what) {

            }

            @Override
            public void onSucceed(int what, Response response) {
            mTx.setText(response.toString());
            }

            @Override
            public void onFailed(int what, Response response) {

            }

            @Override
            public void onFinish(int what) {

            }
        });

    }

    private void getDataByNoGet() {
        //范型就是要存网络获取的元素
        String url = "http://apicloud.mob.com/v1/postcode/pcd?key=26b2b13b4b440";
        Request request= NoHttp.createJsonObjectRequest(url, RequestMethod.GET);
//        Request........
        RequestQueue requestQueue = NoHttp.newRequestQueue();
        requestQueue.add(0, request, new OnResponseListener() {
            @Override
            public void onStart(int what) {//当开始时

            }

            @Override
            public void onSucceed(int what, Response response) {
                mTx.setText(response.toString());

            }

            @Override
            public void onFailed(int what, Response response) {

            }

            @Override
            public void onFinish(int what) {

            }
        });

    }
}

介绍

 NoHttp 是专门做Android网络请求与下载的框架。
    支持HTTP/HTTPS,自动维持Cookie,异步/同步请求,大文件/多文件上传,文件下载;支持304缓存,302/303重定向,支持代理服务器。
    NoHttp特性:
  支持HTTP/HTTPS,自动维持Cookie,异步/同步请求,大文件/多文件上传,文件下载,上传下载均有进度。
  支持304缓存,自定义缓存,302/303重定向,支持代理服务器访问地址(如: Google)。
  NoHttp是队列,自动为请求排队,可以取消指定请求, 可以取消队列所有请求,亦可以停止队列。
  支持请求String、Bitmap、Json、JavaBean,可自定义扩展请求类型。
  Request对象包涵参数、文件、请求头等;Response对象包涵响应内容,响应头等信息,Cookie。
一.AndtoidStudio如何依赖NoHttp
  1.如果仅仅使用HttpURLConnection作为网络层,在app的gralde中添加以下依赖即可:
    1)引用最新版
        compile 'com.yolanda.nohttp:nohttp:+'
    2)引用指定版本
        compile 'com.yolanda.nohttp:nohttp:1.1.0'
  2.如果要使用OkHttp作为网络层,请再依赖(注意两个lib的版本需要一致):
        compile 'com.yanzhenjie.nohttp:okhttp:1.1.0'
  注意:
    不论使用基于HttpURLConnection还是OkHttp的版本,NoHttp的使用方法都不会变,这是NoHttp的优点之一。

二.Eclipse如何依赖NoHttp
  1.如果想依赖源码,请到Github-NoHttp上自行下载源码,然后转为Eclipse的项目格式后导入Eclipse即可。
  2.使用jar包,请在Github-NoHttp上下载NoHttp提供的jar包,copy到你的项目下的libs下即可。
  提示:
    如果你仅仅想用HttpURLConnection只需要下载nohttp.jar即可,如果想使用okhttp的话还要下载nohttp-okhttp.jar,并且需要开发者自自行到okhttp主页下载okhttp的jar,到okio的主页下载okio的jar。

  下载地址:
        https://github.com/yanzhenjie/NoHttp


一.请求
  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.取消请求
1)取消单个请求
Request request = NoHttp.createStringRequest(url);
...
request.cancel();

2)从队列中取消指定的请求
Request request = NoHttp.createStringRequest(url);
request.setCancelSign(sign);
…
queue.cancelBySign(sign);
3)取消队列中所有请求
queue.cancelAll();
4)停止队列
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处理不同的错误,比如超时、网络不好等  
    }  
};
四.自定义请求类型: FastJsonRequest
  1.定义请求对象
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);
五.下载文件
  1.发起下载请求
//下载文件  
downloadRequest = NoHttp.createDownloadRequest(url,
 fielDir, fileName, true, false);  
//what 区分下载  
//downloadRequest 下载请求对象  
//downloadListener 下载监听  
CallServer.getDownloadInstance().add(0, downloadRequest,
 downloadListener);
  2.暂停或者停止下载
    downloadRequest.cancel();
  3.监听下载过程
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) {  
    }  
};

效果图

image.png

你可能感兴趣的:(Android联网第三方框架NoHttp)