Android开发 如何使用OKHttp 一分钟就可以完成

作为目前公认Android开发相对好用的网络请求框架,OkHttp还是相当够资格的,因为大家都在用
其实有的原理不用讲的那么明白,我感觉大家都喜欢直接上代码

第一步:添加依赖

implementation 'com.squareup.okhttp3:okhttp:3.2.0'
implementation 'com.squareup.okhttp3:logging-interceptor:3.8.0'

第二步:创建监听器RequestListener

public interface RequestListener {

    void onSuccess(String json);//成功

    void onFailed(String message);//错误


}

第三步:创建工具类进行请求 HttpUtils
由于这个类需要频繁的使用,需要使用单例模式进行操作,道理就不讲了吧,都懂

private final OkHttpClient okHttpClient;
private static HttpUtils httpUtils = null;
public static HttpUtils getInstance() {
    if (httpUtils == null) {
        synchronized (Object.class) {//类对象在内存中只有一个
            if (httpUtils == null) {
                httpUtils = new HttpUtils();
            }
        }
    }
    return httpUtils;
}

构造方法

private HttpUtils() {
    HttpLoggingInterceptor httpLoggingInterceptor = new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() {
        @Override
        public void log(String message) {
            Log.v("TAG", "TAG" + message);
        }
    });
    httpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
    final Interceptor interceptor = new Interceptor() {
        @Override
        public Response intercept(Chain chain) throws IOException {
            Request request = chain.request().newBuilder().addHeader("headName", "headValue").build();//这个地方的header自己设置
            return chain.proceed(request);
        }
    };
    okHttpClient = new OkHttpClient.Builder()
            .readTimeout(60, TimeUnit.SECONDS)
            .connectTimeout(60, TimeUnit.SECONDS)
            .addInterceptor(interceptor)
            .addInterceptor(httpLoggingInterceptor)
            .build();
}

接下来就是实际操作的代码了
1.get请求

public void doGet(String url, final MyOkListiner listiner){
    Request request = new Request.Builder().url(url).get().build();
    Call call = okHttpClient.newCall(request);
    call.enqueue(new Callback() {
        @Override
        public void onFailure(Call call, IOException e) {
            listiner.onError(e.getMessage());
        }
        @Override
        public void onResponse(Call call, Response response) throws IOException {
            listiner.onOK(response.body().string());
        }
    });
}

2.post请求

public void doPost(String url, HashMap<String,String> map, final MyOkListiner listiner){
    FormBody.Builder builder = new FormBody.Builder();
    Set<Map.Entry<String, String>> entrySet = map.entrySet();
    for (Map.Entry<String,String> entry : entrySet){
        String key = entry.getKey();
        String value = entry.getValue();
        builder.add(key,value);
    }
    FormBody formBody = builder.build();
    Request request = new Request.Builder().url(url).post(formBody).build();
    Call call = okHttpClient.newCall(request);
    call.enqueue(new Callback() {
        @Override
        public void onFailure(Call call, IOException e) {
            listiner.onError(e.getMessage());
        }
        @Override
        public void onResponse(Call call, Response response) throws IOException {
            listiner.onOK(response.body().string());
        }
    });

3.上传文件

public void upload(String url, String path, String filename, String type, final MyOkListiner listiner){
    MultipartBody body = new MultipartBody.Builder()
            .setType(MultipartBody.FORM)
            .addFormDataPart("file", filename, RequestBody.create(MediaType.parse(type), new File(path)))
            .build();
    Request request = new Request.Builder().url(url).post(body).build();
    Call call = okHttpClient.newCall(request);
    call.enqueue(new Callback() {
        @Override
        public void onFailure(Call call, IOException e) {
            listiner.onError(e.getMessage()
            );
        }
        @Override
        public void onResponse(Call call, Response response) throws IOException {
            listiner.onOK(response.body().string());
        }
    });
}

4.下载文件

public void download(String url, final String path, final Myprogress myprogress){
    Request request = new Request.Builder().url(url).get().build();
    Call call = okHttpClient.newCall(request);
    call.enqueue(new Callback() {
        @Override
        public void onFailure(Call call, IOException e) {
            myprogress.onError(e.getMessage());
        }
        @Override
        public void onResponse(Call call, Response response) throws IOException {
            ResponseBody body = response.body();
            long max = body.contentLength();
            InputStream inputStream = body.byteStream();
            FileOutputStream outputStream = new FileOutputStream(path);
            byte[] b=new byte[1024];
            int len=0;
            int count=0;
            while ((len=inputStream.read(b))!=-1){
                count+=len;
                outputStream.write(b,0,len);
                myprogress.onProgress((int) ((count*100)/max));
            }
            if (count>=max){
                myprogress.onFinish();
            }
        }
    });
}

我知道你很懒,完整代码给你贴上吧


public class HttpUtils {

    private OkHttpClient okHttpClient;


    private HttpUtils(){//构造方法只会走一次
        //拦截器
        HttpLoggingInterceptor httpLoggingInterceptor = new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() {
            @Override
            public void log(String message) {
                Log.i("xxx", "xxxx "+message);
            }
        });
        httpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
        //token拦截器
        final Interceptor interceptor = new Interceptor() {
            @Override
            public Response intercept(Chain chain) throws IOException {
                Request request = chain.request().newBuilder().addHeader("token", "werfdwsadfdsaxdfbg").build();
                return chain.proceed(request);
            }
        };
        okHttpClient = new OkHttpClient.Builder()
                .readTimeout(60, TimeUnit.SECONDS)
                .connectTimeout(60, TimeUnit.SECONDS)
                .addInterceptor(interceptor)
                .addInterceptor(httpLoggingInterceptor)
                .build();
    }

    private static HttpUtils httpUtils=null;
    public static HttpUtils getInstance(){
        //双重锁
        if (httpUtils==null){
            synchronized (Object.class){//class对象在内存中只有一个
                if (httpUtils==null){
                    httpUtils = new HttpUtils();
                }
            }
        }
        return httpUtils;
    }

    //get获取数据
    public void doGet(String url, final MyOkListiner listiner){
        Request request = new Request.Builder().url(url).get().build();
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                listiner.onError(e.getMessage());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                listiner.onOK(response.body().string());
            }
        });
    }

    //post获取数据
    public void doPost(String url, HashMap<String,String> map, final MyOkListiner listiner){
        FormBody.Builder builder = new FormBody.Builder();

        Set<Map.Entry<String, String>> entrySet = map.entrySet();
        for (Map.Entry<String,String> entry : entrySet){
            String key = entry.getKey();
            String value = entry.getValue();
            builder.add(key,value);
        }

        FormBody formBody = builder.build();
        Request request = new Request.Builder().url(url).post(formBody).build();

        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                listiner.onError(e.getMessage());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                listiner.onOK(response.body().string());
            }
        });

    }

    //下载
    public void download(String url, final String path, final Myprogress myprogress){
        Request request = new Request.Builder().url(url).get().build();
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                myprogress.onError(e.getMessage());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                ResponseBody body = response.body();
                long max = body.contentLength();

                InputStream inputStream = body.byteStream();
                FileOutputStream outputStream = new FileOutputStream(path);
                byte[] b=new byte[1024];
                int len=0;
                int count=0;
                while ((len=inputStream.read(b))!=-1){
                    count+=len;
                    outputStream.write(b,0,len);
                    myprogress.onProgress((int) ((count*100)/max));
                }
                if (count>=max){
                    myprogress.onFinish();
                }
            }
        });
    }

    //上传
    public void upload(String url, String path, String filename, String type, final MyOkListiner listiner){
        MultipartBody body = new MultipartBody.Builder()
                .setType(MultipartBody.FORM)
                .addFormDataPart("file", filename, RequestBody.create(MediaType.parse(type), new File(path)))
                .build();

        Request request = new Request.Builder().url(url).post(body).build();

        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                listiner.onError(e.getMessage()
                );
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                listiner.onOK(response.body().string());
            }
        });
    }
}

调用自己就会了吧,这里我就不贴了,不会写的再问,我先收工了

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值