Android网络框架-OkHttp3.0总结

一、概述

  OkHttp是Square公司开发的一款服务于android的一个网络框架,主要包含:

  • 一般的get请求
  • 一般的post请求
  • 基于Http的文件上传
  • 文件下载
  • 加载图片
  • 支持请求回调,直接返回对象、对象集合
  • 支持session的保持

  github地址:https://github.com/square/okhttp

二、Http请求

   对于一个Http请求,分为几个步骤:

  1. 创建一个OkhttpClient对象,建议全局只使用一个OkhttpClient 
    OkHttpClient mOkHttpClient = new OkHttpClient.Builder().build;
  2. 创建一个Request对象,包含请求的url地址,请求的方式是get或者post,以及请求的内容
  3. 通过OkhttpClient创建一个newCall,将request包含于其中,类似于将你的request请求封装成了任务
  4. call的执行,有两种执行方式。一种是加入调度队列,call.enqueue,即异步执行call。一种是立即执行,call.execute,即同步执行,会阻塞线程直到请求完成。
  5. 最后就是执行之后的回调函数,注意如果是执行enqueue(),则回调函数不在主线程,如果要执行更新UI界面应将数据通过handler传回主线程
     1 call.enqueue(new Callback(){
     2             @Override
     3             public void onFailure(Call call, IOException e)
     4             {
     5                //执行失败回调函数,call及请求的引用
     6             }
     7 
     8             @Override
     9             public void onResponse(Call call, Response response) throws IOException
    10             {
    11                     //请求成功,获得response,可以通过调用response.body().string()获得服务器返回的数据。response.code()获得请求的状态代码
    12             }
    13 });             
    14     

    以下是完整的get请求实例代码:

 1 //创建okHttpClient对象
 2 OkHttpClient mOkHttpClient = new OkHttpClient.Builder().build;
 3 //创建一个Request
 4 final Request request = new Request.Builder()
 5                 .url("https://github.com/hongyangAndroid")
 6                 .build();
 7 //new call
 8 Call call = mOkHttpClient.newCall(request); 
 9 //请求加入调度
10 call.enqueue(new Callback()
11         {
12             @Override
13             public void onFailure(Request request, IOException e)
14             {
15             }
16 
17             @Override
18             public void onResponse(final Response response) throws IOException
19             {
20                     //String htmlStr =  response.body().string();
21             }
22         });             

三、RequestBody

  对于不同的请求,如get、post、文件上传等等,我们只要构造不同的Request即可。

  1. Get请求,我们可以直接在url里面添加要传递的数据即可
    Request request = new Request.Builder()
        .url("https://github.com/hongyangAndroid")
        .build();
  2. Post请求
    //构建一个表单RequestBody,在里面添加要传递的字段数据
    RequestBody requestBody = new FormBody.Builder()
                    .add("userName",userName)
                    .add("passwd", passwd)
                    .build();
    //将RequestBody传递给Request的Post
    Request request = new Request.Builder()
                    .url(url)
                    .post(requestBody)
                    .build();
  3. 带参数的文件上传
    //建立文件上传请求
    File file = new File(Environment.getExternalStorageDirectory(), "balabala.mp4");
    RequestBody fileRequest = RequestBody.create(MediaType.parse("application/octet-stream"), file);
    //建立表单请求
    RequestBody formRequest = RequestBody.create(null,"xxxx);
    
    //使用MultipartBody将两个RequestBody合在一起
    RequestBody requestBody = new MultipartBody.Builder()
         .setType(MultipartBuilder.FORM)
         .addPart(Headers.of(
              "Content-Disposition", 
              "form-data; name=\"username\""), 
              formRequest)
         .addPart(Headers.of(
             "Content-Disposition", 
             "form-data; name=\"mFile\"; 
             filename=\"wjd.mp4\""), fileRequest)
         .build();

     

四、cookie持久化

  OkHttp提供了非常方便的Cookie管理方法,只要重写一个CookieJar类即可管理Cookie。

 private static OkHttpClient okHttpClient = new OkHttpClient.Builder().cookieJar(new CookieJar() {
        private final ArrayList<Cookie> cookieStore = new ArrayList<Cookie>();

        @Override
        public void saveFromResponse(HttpUrl httpUrl, List<Cookie> list) {
            //当获得一个Response时,会调用这个方法来存储Cookie
            cookieStore.addAll(list);
        }

        @Override
        public List<Cookie> loadForRequest(HttpUrl httpUrl) {
            //当要call一个Request时,会调用这个方法来为请求的head添加cookie
            List<Cookie> cookies = cookieStore;
            return cookies != null ? cookies : new ArrayList<Cookie>();
        }
    }).build();        

 

posted on 2016-03-28 16:40  Yesphet  阅读(996)  评论(0编辑  收藏  举报