okhttp封装okhttp-utils

okhttp-utils

简介:okhttp 的辅助类
更多: 作者    提 Bug    官网   
标签:

由于个人原因,现已停止维护。

对 okhttp 的封装类,okhttp 见:https://github.com/square/okhttp.

目前对应 okhttp 版本3.3.1.

用法

目前对以下需求进行了封装

  • 一般的 get 请求
  • 一般的 post 请求
  • 基于 Http Post 的文件上传(类似表单)
  • 文件下载/加载图片
  • 上传下载的进度回调
  • 支持取消某个请求
  • 支持自定义 Callback
  • 支持 HEAD、DELETE、PATCH、PUT
  • 支持 session 的保持
  • 支持自签名网站 https 的访问,提供方法设置下证书就行

配置 OkhttpClient

默认情况下,将直接使用 okhttp 默认的配置生成 OkhttpClient,如果你有任何配置,记得在 Application 中调用initClient方法进行设置。

public class MyApplication extends Application
{    
    @Override
    public void onCreate()
    {
        super.onCreate();

        OkHttpClient okHttpClient = new OkHttpClient.Builder()
//                .addInterceptor(new LoggerInterceptor("TAG"))
                  .connectTimeout(10000L, TimeUnit.MILLISECONDS)
                  .readTimeout(10000L, TimeUnit.MILLISECONDS)
                  //其他配置
                 .build();

        OkHttpUtils.initClient(okHttpClient);

    }
}

别忘了在 AndroidManifest 中设置。

对于 cookie 一样,直接通过 cookiejar 方法配置,参考上面的配置过程。

CookieJarImpl cookieJar = new CookieJarImpl(new PersistentCookieStore(getApplicationContext()));
OkHttpClient okHttpClient = new OkHttpClient.Builder()
          .cookieJar(cookieJar)
          //其他配置
         .build();

OkHttpUtils.initClient(okHttpClient);

目前项目中包含:

  • PersistentCookieStore //持久化 cookie
  • SerializableHttpCookie //持久化 cookie
  • MemoryCookieStore //cookie 信息存在内存中

如果遇到问题,欢迎反馈,当然也可以自己实现 CookieJar 接口,编写 cookie 管理相关代码。

此外,对于持久化 cookie 还可以使用https://github.com/franmontiel/PersistentCookieJar.

相当于框架中只是提供了几个实现类,你可以自行定制或者选择使用。

对于 Log

初始化 OkhttpClient 时,通过设置拦截器实现,框架中提供了一个LoggerInterceptor,当然你可以自行实现一个 Interceptor 。

 OkHttpClient okHttpClient = new OkHttpClient.Builder()
       .addInterceptor(new LoggerInterceptor("TAG"))
        //其他配置
        .build();
OkHttpUtils.initClient(okHttpClient);

对于 Https

依然是通过配置即可,框架中提供了一个类HttpsUtils

  • 设置可访问所有的 https 网站
HttpsUtils.SSLParams sslParams = HttpsUtils.getSslSocketFactory(null, null, null);
OkHttpClient okHttpClient = new OkHttpClient.Builder()
        .sslSocketFactory(sslParams.sSLSocketFactory, sslParams.trustManager)
         //其他配置
         .build();
OkHttpUtils.initClient(okHttpClient);
  • 设置具体的证书
HttpsUtils.SSLParams sslParams = HttpsUtils.getSslSocketFactory(证书的 inputstream, null, null);
OkHttpClient okHttpClient = new OkHttpClient.Builder()
        .sslSocketFactory(sslParams.sSLSocketFactory, sslParams.trustManager))
         //其他配置
         .build();
OkHttpUtils.initClient(okHttpClient);
  • 双向认证
HttpsUtils.getSslSocketFactory(
    证书的 inputstream, 
    本地证书的 inputstream, 
    本地证书的密码)

同样的,框架中只是提供了几个实现类,你可以自行实现SSLSocketFactory,传入 sslSocketFactory 即可。

其他用法示例

GET 请求

String url = "http://www.csdn.net/";
OkHttpUtils
    .get()
    .url(url)
    .addParams("username", "hyman")
    .addParams("password", "123")
    .build()
    .execute(new StringCallback()
            {
                @Override
                public void onError(Request request, Exception e)
                {

                }

                @Override
                public void onResponse(String response)
                {

                }
            });

POST 请求

 OkHttpUtils
    .post()
    .url(url)
    .addParams("username", "hyman")
    .addParams("password", "123")
    .build()
    .execute(callback);

Post JSON

  OkHttpUtils
    .postString()
    .url(url)
    .content(new Gson().toJson(new User("zhy", "123")))
     .mediaType(MediaType.parse("application/json; charset=utf-8"))
    .build()
    .execute(new MyStringCallback());

提交一个 Gson 字符串到服务器端,注意:传递 JSON 的时候,不要通过 addHeader 去设置 contentType,而使用.mediaType(MediaType.parse("application/json; charset=utf-8")).。

Post File

 OkHttpUtils
    .postFile()
    .url(url)
    .file(file)
    .build()
    .execute(new MyStringCallback());

将文件作为请求体,发送到服务器。

Post 表单形式上传文件

OkHttpUtils.post()//
    .addFile("mFile", "messenger_01.png", file)//
    .addFile("mFile", "test1.txt", file2)//
    .url(url)
    .params(params)//
    .headers(headers)//
    .build()//
    .execute(new MyStringCallback());

支持单个多个文件,addFile的第一个参数为文件的 key,即类别表单中<input type="file" name="mFile"/>的 name 属性。

自定义 CallBack

目前内部包含StringCallBack,FileCallBack,BitmapCallback,可以根据自己的需求去自定义 Callback,例如希望回调 User 对象:

public abstract class UserCallback extends Callback<User>
{
    @Override
    public User parseNetworkResponse(Response response) throws IOException
    {
        String string = response.body().string();
        User user = new Gson().fromJson(string, User.class);
        return user;
    }
}

 OkHttpUtils
    .get()//
    .url(url)//
    .addParams("username", "hyman")//
    .addParams("password", "123")//
    .build()//
    .execute(new UserCallback()
    {
        @Override
        public void onError(Request request, Exception e)
        {
            mTv.setText("onError:" + e.getMessage());
        }

        @Override
        public void onResponse(User response)
        {
            mTv.setText("onResponse:" + response.username);
        }
    });

通过parseNetworkResponse回调的 response 进行解析,该方法运行在子线程,所以可以进行任何耗时操作,详细参见 sample。

下载文件

 OkHttpUtils//
    .get()//
    .url(url)//
    .build()//
    .execute(new FileCallBack(Environment.getExternalStorageDirectory().getAbsolutePath(), "gson-2.2.1.jar")//
    {
        @Override
        public void inProgress(float progress)
        {
            mProgressBar.setProgress((int) (100 * progress));
        }

        @Override
        public void onError(Request request, Exception e)
        {
            Log.e(TAG, "onError :" + e.getMessage());
        }

        @Override
        public void onResponse(File file)
        {
            Log.e(TAG, "onResponse :" + file.getAbsolutePath());
        }
    });

注意下载文件可以使用FileCallback,需要传入文件需要保存的文件夹以及文件名。

显示图片

 OkHttpUtils
    .get()//
    .url(url)//
    .build()//
    .execute(new BitmapCallback()
    {
        @Override
        public void onError(Request request, Exception e)
        {
            mTv.setText("onError:" + e.getMessage());
        }

        @Override
        public void onResponse(Bitmap bitmap)
        {
            mImageView.setImageBitmap(bitmap);
        }
    });

显示图片,回调传入BitmapCallback即可。

上传下载的进度显示

new Callback<T>()
{
    //...
    @Override
    public void inProgress(float progress)
    {
       //use progress: 0 ~ 1
    }
}

callback 回调中有inProgress方法,直接复写即可。

HEAD、DELETE、PUT、PATCH


OkHttpUtils
     .put()//also can use delete() ,head() , patch()
     .requestBody(RequestBody.create(null, "may be something"))//
     .build()//
     .execute(new MyStringCallback());

如果需要 requestBody,例如:PUT、PATCH,自行构造进行传入。

同步的请求

 Response response = OkHttpUtils
    .get()//
    .url(url)//
    .tag(this)//
    .build()//
    .execute();

execute 方法不传入 callback 即为同步的请求,返回 Response。

取消单个请求

 RequestCall call = OkHttpUtils.get().url(url).build();
 call.cancel();

根据 tag 取消请求

目前对于支持的方法都添加了最后一个参数Object tag,取消则通过OkHttpUtils.cancelTag(tag)执行。

例如:在 Activity 中,当 Activity 销毁取消请求:

OkHttpUtils
    .get()//
    .url(url)//
    .tag(this)//
    .build()//

@Override
protected void onDestroy()
{
    super.onDestroy();
    //可以取消同一个 tag 的
    OkHttpUtils.cancelTag(this);//取消以 Activity.this 作为 tag 的请求
}

比如,当前 Activity 页面所有的请求以 Activity 对象作为 tag,可以在 onDestory 里面统一取消。

混淆

#okhttputils
-dontwarn com.zhy.http.**
-keep class com.zhy.http.**{*;}


#okhttp
-dontwarn okhttp3.**
-keep class okhttp3.**{*;}


#okio
-dontwarn okio.**
-keep class okio.**{*;}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值