OkHttp及封装

一. okhttp协议介绍

okhttp是一个第三方类库,用于android中请求网络。
这是一个开源项目,是安卓端最火热的轻量级框架,由移动支付Square公司贡献(该公司还贡献了Picasso和LeakCanary) 。用于替代HttpUrlConnection和Apache HttpClient(android API23 里已移除HttpClient)。
导入依赖

implementation 'com.squareup.okhttp3:okhttp:3.12.1'

二.简单请求方式

1.okhttp完成get请求

OkHttpClient.Builder builder = new OkHttpClient.Builder();
                        builder.connectTimeout(1, TimeUnit.MINUTES);
                        builder.callTimeout(1,TimeUnit.MINUTES);
                        OkHttpClient client = builder.build();
                        Request.Builder builder1 = new Request.Builder();
                        builder1.url("https://raw.githubusercontent.com/zhang721788/testmaterial/master/doctor0.json");
                        builder1.get();
                        Request request = builder1.build();
                        Call call = client.newCall(request);
                        call.enqueue(new Callback() {
                            @Override
                            public void onFailure(Call call, IOException e) {

                            }

                            @Override
                            public void onResponse(Call call, Response response) throws IOException {
                                ResponseBody body = response.body();
                                String json = body.string();
                                Log.i(TAG, "onResponse: "+json);
                            }
                        });

2.okhttp完成post请求

btnPost.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        OkHttpClient client = new OkHttpClient.Builder()
                                .connectTimeout(1,TimeUnit.MINUTES)
                                .callTimeout(1,TimeUnit.MINUTES)
                                .build();
                        FormBody formBody = new FormBody.Builder()
                                .add("name", "1743235924")
                                .add("password", "0321")
                                .build();
                        Request request = new Request.Builder()
                                .put(formBody)
                                .url("https://www.apiopen.top/createUser?key=00d91e8e0cca2b76f515926a36db68f5&")
                                .build();
                        Call call = client.newCall(request);
                        call.enqueue(new Callback() {
                            @Override
                            public void onFailure(Call call, IOException e) {

                            }

                            @Override
                            public void onResponse(Call call, Response response) throws IOException {
                                ResponseBody body = response.body();
                                String json = body.string();
                                Log.i(TAG, "onResponse: "+json);
                            }
                        });

3.okhttp完成下载文件

OkHttpClient client = new OkHttpClient.Builder()
                                .connectTimeout(1, TimeUnit.MINUTES)
                                .callTimeout(1, TimeUnit.MINUTES)
                                .build();
                        Request request = new Request.Builder()
                                .url("http://uvideo.spriteapp.cn/video/2019/0512/56488d0a-7465-11e9-b91b-1866daeb0df1_wpd.mp4")
                                .get()
                                .build();
                        Call call = client.newCall(request);
                        call.enqueue(new Callback() {
                            @Override
                            public void onFailure(Call call, IOException e) {

                            }

                            @Override
                            public void onResponse(Call call, Response response) throws IOException {
                                int count = 0;
                                ResponseBody body = response.body();
                                pb.setMax((int)body.contentLength());
                                InputStream is = body.byteStream();
                                FileOutputStream fos = new FileOutputStream("/sdcard/Movies/a.mp4");
                                int len = 0;
                                byte[] b = new byte[1024];
                                while ((len = is.read(b))!=-1){
                                    fos.write(b,0,len);
                                    count +=len;
                                    pb.setProgress(count);
                                }
                            }
                        });

4.okhttp完成上传文件

OkHttpClient client = new OkHttpClient.Builder()
                                .connectTimeout(1, TimeUnit.MINUTES)
                                .callTimeout(1, TimeUnit.MINUTES)
                                .build();
                        MultipartBody multipartBody = new MultipartBody.Builder()
                                .setType(MultipartBody.FORM)
                                .addFormDataPart("file", "abc.mp4", RequestBody.create(MediaType.parse("media/mp4"), new File("/sdcard/Movies/a.mp4")))
                                .build();
                        Request request = new Request.Builder()
                                .url("http://169.254.12.37/ic/")
                                .post(multipartBody)
                                .build();
                        Call call = client.newCall(request);
                        call.enqueue(new Callback() {
                            @Override
                            public void onFailure(Call call, IOException e) {
                                Log.i(TAG, "onFailure: "+e.getLocalizedMessage());
                            }

                            @Override
                            public void onResponse(Call call, Response response) throws IOException {

                            }
                        });

okhttp封装

1.定义回调接口

public interface OkhttpListen {
    void onError(String mesage);//返回错误信息
    void onSuccess(String json);//返回数据
}
public interface OkHttpProgressListen {
    void setMax(int max);//设置最大值
    void setProgress(int progress);//设置当前进度
    void onFinish();//下载完成
    void onError(String message);//错误
}

2.工具类

import android.util.Log;

import com.example.thefirstweek.PackagingOkHttp.listener.OkHttpProgressListen;
import com.example.thefirstweek.PackagingOkHttp.listener.OkhttpListen;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.logging.HttpLoggingInterceptor;

public class OkHttpUtil {

    private static final String TAG = "OkHttpUtil";

    private OkHttpClient okHttpClient = null;

    private OkHttpUtil() {
   	    //log拦截器
        HttpLoggingInterceptor httpLoggingInterceptor=new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() {
            @Override
            public void log(String message) {
                Log.i(TAG, "OkHttpUtil: "+message);
            }
        });

        httpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
		//token拦截器
        Interceptor interceptor = new Interceptor() {

            @Override
            public Response intercept(Chain chain) throws IOException {
                Request request = chain.request().newBuilder().build();
                return chain.proceed(request);
            }
        };

        okHttpClient = new OkHttpClient.Builder()
                .connectTimeout(1, TimeUnit.MINUTES)
                .callTimeout(1, TimeUnit.MINUTES)
                .addInterceptor(interceptor)
                .addInterceptor(httpLoggingInterceptor)
                .build();
    }

    private static OkHttpUtil okHttpUtil = null;

    public static OkHttpUtil getInstance(){
        if(okHttpUtil == null){
            synchronized (Object.class){
                if(okHttpUtil == null){
                    okHttpUtil = new OkHttpUtil();
                }
            }
        }
        return okHttpUtil;
    }

    public void doGet(String url, final OkhttpListen okhttpListen){

        final Request request = new Request.Builder()
                .url(url)
                .get()
                .build();

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

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        String json = response.body()
                                .string();
                        okhttpListen.onSuccess(json);
                    }
                });
    }

    public void doPost(String url, HashMap<String,String> hashMap, final OkhttpListen okhttpListen){
        FormBody.Builder builder = new FormBody.Builder();
        Set<Map.Entry<String, String>> entrySet = hashMap.entrySet();
        Iterator<Map.Entry<String, String>> iterator = entrySet.iterator();
        while (iterator.hasNext()){
            Map.Entry<String, String> entry = iterator.next();
            builder.add(entry.getKey(),entry.getValue());
        }
        FormBody formBody = builder.build();

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

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

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        String json = response.body()
                                .string();
                        okhttpListen.onSuccess(json);
                    }
                });
    }

    public void doDown_Load(String url, final String path, final OkHttpProgressListen okhttpProgressListen){

        final Request request = new Request.Builder()
                .url(url)
                .get()
                .build();

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

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        int progress = 0;
                        InputStream is = response.body()
                                .byteStream();
                        FileOutputStream fos = new FileOutputStream(path);
                        int len = 0;
                        byte[] b = new byte[1024];
                        while ((len = is.read(b)) != -1){
                            fos.write(b,0,len);
                            progress += len;
                            okhttpProgressListen.setProgress(progress);
                        }
                        okhttpProgressListen.setMax((int) response.body().contentLength());
                        okhttpProgressListen.onFinish();
                    }
                });
    }

    public void doUp_Load(String url, final String path, String filename,String type, final OkHttpProgressListen okhttpProgressListen){

        MultipartBody multipartBody = new MultipartBody.Builder()
                .setType(MultipartBody.FORM)
                .addFormDataPart("file", filename, RequestBody.create(MediaType.parse(type), new File(path)))
                .build();

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

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

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        okhttpProgressListen.onFinish();
                    }
                });
    }

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值