Okhttp 使用详解

一, OKHttp介绍

okhttp是一个第三方类库,用于android中请求网络。

这是一个开源项目,是安卓端最火热的轻量级框架,由移动支付Square公司贡献(该公司还贡献了Picasso和LeakCanary) 。
用于替代HttpUrlConnection和Apache HttpClient(android API23 里已移除HttpClient)。

okhttp有自己的官网,官网网址:[OKHttp官网](http://square.github.io/okhttp/)

如果想了解原码可以在github上下载,地址是:[https://github.com/square/okhttp](https://github.com/square/okhttp)

在AndroidStudio中使用不需要下载jar包,直接添加依赖即可: 
compile ‘com.squareup.okhttp3:okhttp:3.4.1’

二、使用

OkHttp3开发三部曲:
1、创建OkHttpClient,添加配置
2、创建请求
3、执行请求
下面分别来说说这三个步骤:

1. 创建OkHttpClient

一个最简单的OkHttpClient

OkHttpClient okHttpClient=new OkHttpClient.Builder().build(); 

一个复杂点的OkHttpClient配置

File cacheDir = new File(getCacheDir(), "okhttp_cache");  
//File cacheDir = new File(getExternalCacheDir(), "okhttp");  
Cache cache = new Cache(cacheDir, 10 * 1024 * 1024);  
  
okHttpClient = new OkHttpClient.Builder()  
            .connectTimeout(5*1000, TimeUnit.MILLISECONDS) //链接超时  
            .readTimeout(10*1000,TimeUnit.MILLISECONDS) //读取超时  
            .writeTimeout(10*1000,TimeUnit.MILLISECONDS) //写入超时  
            .addInterceptor(new HttpHeadInterceptor()) //应用拦截器:统一添加消息头  
            .addNetworkInterceptor(new NetworkspaceInterceptor())//网络拦截器  
            .addInterceptor(loggingInterceptor)//应用拦截器:打印日志  
            .cache(cache)  //设置缓存  
            .build(); 

具体可配置参数见OkHttpClient.Builder类,几点注意事项:

1.拦截器

两种拦截器:Interceptor(应用拦截器)、NetworkInterceptor(网络拦截器)

两种拦截器的区别

1)Interceptor比NetworkInterceptor先执行
2)同一种Interceptor倒序返回
   A(start)----B(start)----B(end)----A(end)
因此上面配置的Interceptor执行顺序如下
HttpHeadInterceptor start----LoggingInterceptor start----LoggingInterceptor end---HttpHeadInterceptor end
 3)日志拦截器
自定义日志拦截器
public class LoggingInterceptor implements Interceptor {  
  private static final String TAG="Okhttp";  
  @Override public Response intercept(Interceptor.Chain chain) throws IOException {  
    Request request = chain.request();  
  
    long t1 = System.nanoTime();  
    Log.d(TAG,String.format("Sending request %s on %s%n%s",  
        request.url(), chain.connection(), request.headers()));  
  
    Response response = chain.proceed(request);  
    long t2 = System.nanoTime();  
    Log.d(TAG,String.format("Received response for %s in %.1fms%n%s",  
        response.request().url(), (t2 - t1) / 1e6d, response.headers()));  
  
    MediaType mediaType = response.body().contentType();  
    String content = response.body().string();  
    Log.d(TAG,content);  
  
    response=response.newBuilder()  
                    .body(ResponseBody.create(mediaType,content))  
                    .build();  
    return response;  
  }  
}  

官方提供的Logging Interceptor

地址:https://github.com/victorfan336/okhttp-logging-interceptor
gradle.build中添加依赖:
compile 'com.squareup.okhttp3:logging-interceptor:3.1.2'

使用方法
HttpLoggingInterceptor logging = new HttpLoggingInterceptor();  
logging.setLevel(Level.BODY);//日志级别,Body级别打印的信息最全面  
OkHttpClient client = new OkHttpClient.Builder()  
  .addInterceptor(logging)  
  .build();  

2、注意

开发中应该只维护一个OkHttpClient实例,这样可以复用连接池、线程池等,避免性能开销
如果想修改参数,可通过
okHttpClient.newBuilder()修改,这样可以复用okHttpClient之前的所有配置,
比如想针对某个请求修改链接超时。

OkHttpClient newClient=okHttpClient.newBuilder()  
       .connectTimeout(10*1000,TimeUnit.MILLISECONDS)  
       .build();  
newClient.newCall(req);   

二、创建请求

GET请求

通过Request.Builder创建请求,默认是Get请求

Request req = new Request.Builder().url(url).build();  
Call call = okHttpClient.newCall(req);  

POST请求

主要是构建RequestBody,并设置Content-Type消息头。

1.普通Post请求

比如json请求

RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), jsonObject.toString());  
Request req = new Request.Builder().url(url)  
        .post(requestBody)  
        .build();  
Call call = okHttpClient.newCall(req);  

2. 使用FormBody传递键值对参数
Content-Type: application/x-www-form-urlencoded
比如:

RequestBody requestBody =  
            new FormBody.Builder()  
                    .add("username", "zhangsan")  
                    .add("password", "1111111")  
                    .build();  
Request req = new Request.Builder().url(url).post(uploadBody).build();  
Call call = okHttpClient.newCall(req);

3. 使用RequestBody传递Json或File对象

RequestBody是抽象类,故不能直接使用,但是他有静态方法create,使用这个方法可以得到RequestBody对象。

这种方式可以上传Json对象或File对象。 
上传json对象使用示例如下:

OkHttpClient client = new OkHttpClient();//创建OkHttpClient对象。
MediaType JSON = MediaType.parse("application/json; charset=utf-8");//数据类型为json格式,
String jsonStr = "{\"username\":\"lisi\",\"nickname\":\"李四\"}";//json数据.
RequestBody body = RequestBody.create(JSON, josnStr);
Request request = new Request.Builder()
        .url("http://www.baidu.com")
        .post(body)
        .build();
client.newCall(request).enqueue(new Callback() {
    ...
});//此处省略回调方法。
上传File对象使用示例如下:

OkHttpClient client = new OkHttpClient();//创建OkHttpClient对象。
MediaType fileType = MediaType.parse("File/*");//数据类型为json格式,
File file = new File("path");//file对象.
RequestBody body = RequestBody.create(fileType , file );
Request request = new Request.Builder()
        .url("http://www.baidu.com")
        .post(body)
        .build();
client.newCall(request).enqueue(new Callback() {。。。});//此处省略回调方法。

4. 使用MultipartBody同时传递键值对参数和File对象

这个字面意思是多重的body。我们知道FromBody传递的是字符串型的键值对,RequestBody传递的是多媒体,那么如果我们想二者都传递怎么办?
此时就需要使用MultipartBody类。 
使用示例如下:

OkHttpClient client = new OkHttpClient();
MultipartBody multipartBody =new MultipartBody.Builder()
        .setType(MultipartBody.FORM)
        .addFormDataPart("groupId",""+groupId)//添加键值对参数
        .addFormDataPart("title","title")
        .addFormDataPart("file",file.getName(),RequestBody.create(MediaType.parse("file/*"), file))//添加文件
        .build();
final Request request = new Request.Builder()
        .url(URLContant.CHAT_ROOM_SUBJECT_IMAGE)
        .post(multipartBody)
        .build();
client.newCall(request).enqueue(new Callback() {。。。});
Request req = new Request.Builder().url(url).post(uploadBody).build();  
okHttpClient.newCall(req);  

5. 使用MultipartBody提交分块请求

MultipartBody 可以构建复杂的请求体,与HTML文件上传形式兼容。
多块请求体中每块请求都是一个请求体,可以定义自己的请求头,这些请求头可以用来描述这块请求。
例如他的Content-Disposition。如果Content-Length和Content-Type可用的话,他们会被自动添加到请求头中。

private static final String IMGUR_CLIENT_ID = "...";
private static final MediaType MEDIA_TYPE_PNG = MediaType.parse("image/png");
private void postMultipartBody() {
    OkHttpClient client = new OkHttpClient();
    // Use the imgur image upload API as documented at https://api.imgur.com/endpoints/image
    MultipartBody body = new MultipartBody.Builder("AaB03x")
            .setType(MultipartBody.FORM)
            .addPart(
                    Headers.of("Content-Disposition", "form-data; name=\"title\""),
                    RequestBody.create(null, "Square Logo"))
            .addPart(
                    Headers.of("Content-Disposition", "form-data; name=\"image\""),
                    RequestBody.create(MEDIA_TYPE_PNG, new File("website/static/logo-square.png")))
            .build();

    Request request = new Request.Builder()
            .header("Authorization", "Client-ID " + IMGUR_CLIENT_ID)
            .url("https://api.imgur.com/3/image")
            .post(body)
            .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 {
            System.out.println(response.body().string());

        }
    });
}

6. 自定义RequestBody实现流的上传

在上面的分析中我们知道,只要是RequestBody类以及子类都可以作为post方法的参数,下面我们就自定义一个类,继承RequestBody,实现流的上传。 
使用示例如下: 
首先创建一个RequestBody类的子类对象:

RequestBody body = new RequestBody() {
    @Override
    public MediaType contentType() {
        return null;
    }

    @Override
    public void writeTo(BufferedSink sink) throws IOException {//重写writeTo方法
        FileInputStream fio= new FileInputStream(new File("fileName"));
        byte[] buffer = new byte[1024*8];
        if(fio.read(buffer) != -1){
             sink.write(buffer);
        }
    }
};
然后使用body对象:

OkHttpClient client = new OkHttpClient();//创建OkHttpClient对象。
Request request = new Request.Builder()
        .url("http://www.baidu.com")
        .post(body)
        .build();
client.newCall(request).enqueue(new Callback() {。。。});

以上代码的与众不同就是body对象,这个body对象重写了write方法,里面有个sink对象。这个是OKio包中的输出流,有write方法。使用这个方法我们可以实现上传流的功能。

使用RequestBody上传文件时,并没有实现断点续传的功能。我可以使用这种方法结合RandomAccessFile类实现断点续传的功能。

三、执行请求

1、同步执行

Response response = call.execute();  

由于android强制要求网络请求在线程中执行,所以无法使用execute

2、异步执行

call.enqueue(new Callback() {  
    @Override  
    public void onFailure(Call call, IOException e) {  
        //失败回调  
    }  
  
    @Override  
    public void onResponse(Call call, Response response) throws IOException {  
         //成功回调,当前线程为子线程,如果需要更新UI,需要post到主线程中  
       
        boolean successful = response.isSuccessful();  
        //响应消息头  
        Headers headers = response.headers();  
        //响应消息体  
        ResponseBody body = response.body();  
        String content=response.body().string());  
        //缓存控制  
        CacheControl cacheControl = response.cacheControl();  
          
    }  
});  

1)Response:封装了网络响应消息,比如响应消息头、缓存控制、响应消息体等。
    String content=response.body().string(); //获取字符串
    InputStream inputStream = response.body().byteStream();//获取字节流(比如下载文件)

2)Callback回调是在子线程中执行的,如果要更新UI,请post到主线程中。

三、其他设置

1. 设置请求头

OKHttp中设置请求头特别简单,在创建request对象时调用一个方法即可。 
使用示例如下:

Request request = new Request.Builder()
                .url("http://www.baidu.com")
                .header("User-Agent", "OkHttp Headers.java")
                .addHeader("token", "myToken")
                .build();

2. 设置超时

没有响应时使用超时结束call。没有响应的原因可能是客户点链接问题、服务器可用性问题或者这之间的其他东西。OkHttp支持连接,读取和写入超时。

Request request = new Request.Builder()
                .url("http://www.baidu.com")
                .connectTimeout(10, TimeUnit.SECONDS);//连接超时
                .readTimeout(10,TimeUnit.SECONDS);//读取超时
                .writeTimeout(10,TimeUnit.SECONDS);//写入超时
                .build();

3. 设置缓存

为了缓存响应,你需要一个你可以读写的缓存目录,和缓存大小的限制。这个缓存目录应该是私有的,不信任的程序应不能读取缓存内容。 
一个缓存目录同时拥有多个缓存访问是错误的。大多数程序只需要调用一次new OkHttpClient(),在第一次调用时配置好缓存,然后其他地方只需要调用这个实例就可以了。否则两个缓存示例互相干扰,破坏响应缓存,而且有可能会导致程序崩溃。 
响应缓存使用HTTP头作为配置。你可以在请求头中添加Cache-Control: max-stale=3600 ,OkHttp缓存会支持。你的服务通过响应头确定响应缓存多长时间,例如使用Cache-Control: max-age=9600。

int cacheSize = 10 * 1024 * 1024; // 10 MiB
Cache cache = new Cache(cacheDirectory, cacheSize);

OkHttpClient.Builder builder = new OkHttpClient.Builder();
builder.cache(cache);
OkHttpClient client = builder.build();

Request request = new Request.Builder()
        .url("http://publicobject.com/helloworld.txt")
        .build();

Call call = client.newCall(request);
call.enqueue(new Callback() {
        ...
});

Okhttp使用上的一些缺点

1、对于Get请求,如果请求参数较多,自己拼接Url较为麻烦

比如

HttpUrl httpUrl = new HttpUrl.Builder()  
               .scheme("http")  
               .host("www.baidu.com")  
               .addPathSegment("user")  
               .addPathSegment("login")  
               .addQueryParameter("username", "zhangsan")  
               .addQueryParameter("password","123456")  
               .build();  

拼接结果:http://www.baidu.com/user/login/username=zhangsan&password=123456

如果能做一些封装,直接addParam(key,value)的形式则会简单很多。

2、Callback在子线程中回调,大部分时候,我们都是需要更新UI的,还需自己post到主线程中处理。
3、构建请求步骤比较多
因此,Square提供了针对OkHttp的封装库Retrofit,另外Github上也有很多第三方的封装库,比如OkGo。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值