OkHttp的使用

网络请求框架我一直都使用httpclient,后来改成了xutils,但是去年开始自从Android6.0去掉了httpclient的支持,想要使用还要在build.gradle添加useLibrary 'org.apache.http.legacy',加上google的推广,Okhttp变得非常火了起来,于是自己也修改自己的网络框架。
我使用时OkHttp已经出现3.0的版本了,与2.0的版本还是有一些差别的

get

基本上没有什么区别

2.0

OkHttpClient client = new OkHttpClient();
client.setConnectTimeout(15,TimeUnit.SECONDS);
client.setWriteTimeout(20,TimeUnit.SECONDS);    
client.setReadTimeout(20,TimeUnit.SECONDS);
Request request = new Request.Builder().url(url).build();
Response response = client.newCall(request).execute();

3.0

OkHttpClient client = new OkHttpClient();
client.newBuilder().connectTitmeout(15,TimeUnit.SECONDS)
client.newBuilder().readTimeout(15,TimeUnit.SECONDS)
client.newBuilder().wirteTimeout(15,TimeUnit.SECONDS)
Request request = new Request.Builder().url(url).build();
Response response = client.newCall(request).execute();

post

取消了FormEncodingBuilder使用FormBody

2.0

OkHttpClient client = new OkHttpClient();
RequestBody requestBody = new FormEncodingBuilder() .add("","").add("","").build();
Request request = new Request.Builder().url(url).post(requestBody).build();
Response response = client.newCall(request).execute();

3.0

OkHttpClient client = new OkHttpClient();
RequestBody requestBody = new FormBody.Builder().add("","").add("","").build();
Request request = new Request.Builder().url(url).post(requestBody).build();
Response response = client.newCall(request).execute();

上传文件

MultipartBuilder改为MultipartBody

2.0

OkHttpClient client = new OkHttpClient();
MultipartBuilder multipartEntity = new MultipartBuilder().type(MultipartBuilder.FORM);  
File file = new File(tmepName);
RequestBody fileBody = RequestBody.create(MediaType.parse("image/*"), file);
multipartEntity.addFormDataPart(key,file.getName(), fileBody);
multipartEntity.addFormDataPart(key, value);
RequestBody requestBody = multipartEntity.build();
Request request = new Request.Builder().url(url).post(requestBody).build();
Response response = client.newCall(request).execute();

3.0

OkHttpClient client = new OkHttpClient();
MultipartBody.Builder multipartEntity = new MultipartBody.Builder();
File file = new File(tmepName);
RequestBody fileBody = RequestBody.create(MediaType.parse("image/*"), file);
multipartEntity.addFormDataPart(key,file.getName(), fileBody);
multipartEntity.addFormDataPart(key, value);
RequestBody requestBody = multipartEntity.build();
Request request = new Request.Builder().url(url).post(requestBody).build();
Response response = client.newCall(request).execute();

cookie

使用cookieJar替代cookieHandler
持久化文件

2.0

client.setCookieHandler(new CokieManager(new PersistentCookieStore(context), CookiePolicy.ACCEPT_ALL));

3.0

client.newBuilder().cookieJar(new CookiesManager());

以上就是OkHttp的简单使用以及2.0与3.0的差异,下一篇我们讲解retrofit。

你可能感兴趣的:(OkHttp的使用)