okhttp封装

#okhttpcontenuitls

/**

  • 原则:代码复用性+只有一个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 request = chain.request();//获得request对象
    // Request.Builder builder = request.newBuilder();//通过request获得builder
    // builder.header(“token”,“1705B”);//设置请求头
    // Request request1 = builder.build();//添加了token的request
    Request request1=chain.request().newBuilder().header(“token”,“1705B”).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 voliate OkhttpUtils okhttpUtils=null;
    //公开方法
    public static OkhttpUtils getInstance(){
    //双重校验锁:
    if(okhttpUtilsnull){
    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<String,String> map, final MyOkListener listener){
      //TODO 请求体
      FormBody.Builder builder1 = new FormBody.Builder();
      Set<Map.Entry<String, String>> entries = map.entrySet();//键值对的集合
      for (Map.Entry<String, String> 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();
       
           //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;
              	int progress= count*100/max;
               listener.setProgress(progress);//通知进度
           }
           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();
       }
      

      });

    }
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值