okhttp

android网络框架之OKhttp

一个处理网络请求的开源项目,是安卓端最火热的轻量级框架,由移动支付Square公司贡献
HTTP是现代应用程序网络的方式。这是我们交换数据和媒体的方式。高效地执行HTTP可以使您的工作负载更快,并节省带宽。

OkHttp是一个默认高效的HTTP客户端:

HTTP/2支持允许对同一主机的所有请求共享一个套接字。
连接池减少了请求延迟(如果HTTP/2不可用)。
透明GZIP压缩下载大小。
响应缓存完全避免了网络重复请求。

当网络出现问题时,OkHttp会坚持下去:它会从常见的连接问题中悄悄地恢复。如果您的服务有多个IP地址,如果第一个连接失败,OkHttp将尝试替代地址。这对于IPv4+IPv6和托管在冗余数据中心中的服务是必要的。OkHttp支持现代TLS特性(TLS 1.3、ALPN、证书固定)。可以将其配置为后退以实现广泛的连接。

使用OkHttp很容易。它的请求/响应API设计为流畅的构建器和不变性。它同时支持同步阻塞调用和带回调的异步调用。

http协议:

HTTP,超文本传输协议,英文全称是Hypertext Transfer Protocol,它是互联网上应用最为广泛的一种网络协议。HTTP是一种应用层协议,它是基于TCP协议之上的请求/响应式的协议,即一个客户端与服务器建立连接后,向服务器发送一个请求;服务器接到请求后,给予相应的响应信息。

请求协议和响应协议

请求协议:
①请求首行:
②请求头信息:客户端告诉服务器我这边的信息
③空行
④请求体:get请求是没有请求体的
响应协议:
①响应首行:HTTP/1.1 200 OK
②响应头信息:Content-Length 服务器返回数据的总大小
③空行
④响应体:服务器返回的数据

okhttp-Get请求

//网络请求json串
    public void getjson(){
        //TODO 1:client
        OkHttpClient.Builder builder = new OkHttpClient.Builder();
        builder.callTimeout(5, TimeUnit.SECONDS);//连接超时
        builder.readTimeout(5,TimeUnit.SECONDS);//读取超时
        OkHttpClient client = builder.build();
        //TODO 2:request对象
        Request.Builder builder1 = new Request.Builder();
        builder1.url("http://www.qubaobei.com/ios/cf/dish_list.php?stage_id=1&limit=20&");//设置网址
        builder1.get();//设置请求方法
        Request request = builder1.build();
        //TODO 3:发起连接call
        Call call = client.newCall(request);
        //TODO 4:通过call得到response
        call.enqueue(new Callback() {
            //请求失败
            @Override
            public void onFailure(Call call, IOException e) {
            }
            //请求成功
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                //获得响应体:json串
                ResponseBody body = response.body();
                //通过body直接转成字符串
                String json = body.string();
               // Toast.makeText(MainActivity.this, ""+json, Toast.LENGTH_SHORT).show();
                Message obtain = Message.obtain();
                obtain.what=GET_JSON_OK;
                obtain.obj=json;
                handler.sendMessage(obtain);

            }
        });
    }

okhttp-Post请求

//post请求完成注册
    private void zhuce() {
        OkHttpClient client = new OkHttpClient.Builder()
                .callTimeout(5, TimeUnit.SECONDS)
                .readTimeout(5, TimeUnit.SECONDS)
                .build();
        //请求体:phone=13594347817&passwd=123654
        FormBody formBody = new FormBody.Builder()
                .add("phone", "13594343356")
                .add("passwd", "123654")
                .build();
        final Request request = new Request.Builder()
                .url("https://www.apiopen.top/createUser?key=00d91e8e0cca2b76f515926a36db68f5&")
                .post(formBody)//post提交必须要设置请求体
                .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 {
                String string = response.body().string();
                Message obtain = Message.obtain();
                obtain.what=GET_JSON_OK;
                obtain.obj=string;
                handler.sendMessage(obtain);
            }
        });
    }

okhttp-download

//下载文件到SD卡中
    private void sd() {
        //TODO 1:client
        OkHttpClient client = new OkHttpClient.Builder()
                .readTimeout(5, TimeUnit.SECONDS)
                .callTimeout(5, TimeUnit.SECONDS)
                .build();
        //TODO 2:request
        Request request = new Request.Builder()
                .get()
                .url("http://169.254.113.244/hfs/a.jpg")
                .build();
        //TODO 3:call
        Call call = client.newCall(request);
        //TODO 4:response
        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();
                long l = body.contentLength();//获得总大小
                InputStream inputStream = body.byteStream();//响应体-->输入流
                //边读边写
            }
        });
    }

okhttp-upload

private void upload() throws IOException {
        OkHttpClient client = new OkHttpClient.Builder()
                .callTimeout(5, TimeUnit.SECONDS)
                .readTimeout(5, TimeUnit.SECONDS)
                .build();
        //上传文件的请求体
        MultipartBody requestBody = new MultipartBody.Builder()
                .setType(MultipartBody.FORM)
                .addFormDataPart("file", "music.mp3",//music.mp3 服务器端的名字
                        RequestBody.create(MediaType.parse("media/mp3"), new File("/sdcard/李伯伯.mp3")))
                .build();
        final Request request = new Request.Builder()
                .url("http://<--ip地址-->/hfs")
                .post(requestBody)//post提交必须要设置请求体
                .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 {
                
            }
        });
    }

okhttp封装

1.接口回调

public interface MyOkListener {
     void onError(String mesage);//返回错误信息
      void onSuccess(String json);//返回数据
}

public interface MyFileListener {
    void setMax(int max);//设置最大值
    void setProgress(int progress);//设置当前进度
    void onFinish();//下载完成
    void onError(String message);//错误
}

2.定义管理类

/**
 * 原则:代码复用性+只有一个Client对象
 *
 *
 * */
public class OkhttpUtils {
    private OkHttpClient okHttpClient;//在构造方法里面创建

    //单例模式:构造私有化
    private OkhttpUtils(){//只会创建一次
        //log拦截器
        HttpLoggingInterceptor httpLoggingInterceptor=new HttpLoggingInterceptor();
        httpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
        //token拦截器
        Interceptor tokenInterceptor=new Interceptor() {
            @Override
            public Response intercept(Chain chain) throws IOException {

                Request request1=chain.request().newBuilder().header("token","zxc").build();
                return chain.proceed(request1);
            }
        };
        okHttpClient=new OkHttpClient.Builder()
                .readTimeout(5, TimeUnit.SECONDS)
                .connectTimeout(5, TimeUnit.SECONDS)
                .addInterceptor(tokenInterceptor)//添加token拦截器,一定要在log拦截器之前设置
                .addInterceptor(httpLoggingInterceptor)//添加log拦截器
                .build();

    };
    //自行实例化
    private static  OkhttpUtils okhttpUtils=null;
    //公开方法
    public static OkhttpUtils getInstance(){
        //双重校验锁:
        if(okhttpUtils==null){
            synchronized (StringBuilder.class){
                if(okhttpUtils==null){
                    okhttpUtils=new OkhttpUtils();
                }
            }
        }
        return  okhttpUtils;
    }
    /***
     * @param str_url  网址
     * @param listener  回调 将请求的结果返回给Activitt
     */
    public  void doget(String str_url, final MyOkListener listener){
        //TODO 2:request对象
        Request request=new Request.Builder().url(str_url).get().header("Connection","Keep-Alive").build();
        //TODO 3:call
        Call call = okHttpClient.newCall(request);
        //TODO 4:加入队列 得到response
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                listener.onError(e.getMessage());
            }
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                listener.onSuccess(response.body().string());
            }
        });
    }
    /***
     *
     * @param str_url 请求网址
     * @param listener 回调的监听
     * @param map  请求体参数
     */
    public void dopost(String str_url, HashMap map, final MyOkListener listener){
        //TODO 请求体
        FormBody.Builder builder1 = new FormBody.Builder();
        Set> entries = map.entrySet();//键值对的集合
        for (Map.Entry entry : entries) {//遍历集合
            String key = entry.getKey();//获得键
            String value = entry.getValue();//获得值
            builder1.add(key,value);
        }
        FormBody formBody = builder1.build();
        //TODO 2:request对象
        Request request = new Request.Builder().url(str_url).post(formBody).build();
        //TODO 3:call
        Call call = okHttpClient.newCall(request);
        //TODO 4:加入队列 得到response
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                listener.onError(e.getMessage());
            }
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                listener.onSuccess(response.body().string());
            }
        });
    }

    /***
     * @param str_url 网址
     * @param path 下载地址
     * @param listener 监听
     */
    public void download(String str_url, final String path, final MyFileListener listener){
        //TODO 1:request对象
        Request request = new Request.Builder()
                .url(str_url)
                .get()
                //③”Accept-Encoding”, “identity”
                .header("Accept-Encoding","identity")
                .build();
        //TODO 2:客户端发起连接得到call
        Call call = okHttpClient.newCall(request);
        //TODO 3:加入队列得到response
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                listener.onError(e.getMessage());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                ResponseBody body = response.body();
                //TODO 1:获得总长度
                long max = body.contentLength();
                listener.setMax((int) max);//返回最大值
                //TODO 2:得到输入流
                InputStream inputStream = body.byteStream();
                FileOutputStream fileOutputStream = new FileOutputStream(path);
                byte[] bytes=new byte[1024];
                int len=0;
                int count=0;
                while((len=inputStream.read(bytes))!=-1){
                    fileOutputStream.write(bytes,0,len);
                    count+=len;
                    listener.setProgress(count);//通知进度
                }
                listener.onFinish();//通知完成
            }
        });


    }

    /****
     *
     * @param str_url 请求网址
     * @param path 上传文件的路径
     * @param filename  上传到服务器那边生成文件的名称
     * @param type  类型
     * @param listener  监听
     */
    public void upload(String str_url, String path, String filename,String type, final MyFileListener listener){
        //请求体如何设置
        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(str_url).post(body).build();
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                listener.onError(e.getMessage());
            }

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

    }
}

你可能感兴趣的:(okhttp)