OKHttp
Android Studio 配置gradle:
compile 'com.squareup.okhttp3:okhttp:3.3.1'
基本使用
异步get请求:
OKHttp采用了生成器模式,每个Builder里有个Dispatcher对象,这个对象负责异步请求。
public voidgetAsyncHttp(View v) {
OkHttpClient.Builder mClient =newOkHttpClient().newBuilder();
mClient.authenticator(newAuthenticator() {
@Override
publicRequestauthenticate(Route route,Response response)throwsIOException {
return null;
}
});
finalRequest request =newRequest.Builder().url("http://www.baidu.com")
.build();
finalCall call = mClient.build().newCall(request);
//进入队列,就是包装进一个runnable放入队列
call.enqueue(newCallback() {
@Override
public voidonFailure(Call call,IOException e) {
}
@Override
public voidonResponse(Call call,Response response)throwsIOException {
Log.e(TAG,"onResponse: cache : "+" ==="+ response.networkResponse().toString());
//回掉并不是在主线程
runOnUiThread(newRunnable() {
@Override
public voidrun() {
Toast.makeText(getApplicationContext(),"异步GET请求 OK !",Toast.LENGTH_SHORT).show();
}
});
}
});
}
同步get请求:
public voidgetSyncHttp(View v)throwsIOException {
OkHttpClient mClient =newOkHttpClient();
Request request =newRequest.Builder().url("http://www.baidu.com").build();
finalCall call = mClient.newCall(request);
//同步请求需要在子线程中执行
newThread(newRunnable() {
@Override
public voidrun() {
Response response =null;
try{
response =call.execute();
}catch(IOException e) {
e.printStackTrace();
}
if(response.isSuccessful()) {
try{
Log.e(TAG,"getSyncHttp: "+ response.body().string());
}catch(IOException e) {
e.printStackTrace();
}
}else{
try{
throw newIOException("Unexpected code "+ response);
}catch(IOException e) {
e.printStackTrace();
}
}
}
}).start();
}
异步post请求:
public voidpostAsynHttp(View v) {
OkHttpClient mClient =newOkHttpClient();
RequestBody requestBody =newFormBody.Builder().add("size","10")
.add("app","weather")
.build();
Request request =newRequest.Builder().url("http://api.1-blog.com/biz/bizserver/article/list.do")
.post(requestBody).build();
Call call = mClient.newCall(request);
call.enqueue(newCallback() {
@Override
public voidonFailure(Call call,IOException e) {
}
@Override
public voidonResponse(Call call,Response response)throwsIOException {
}
});
}
设置缓存:
private voidsetCache(OkHttpClient.Builder mClient) {
File externalCacheDir = getExternalCacheDir();
intcacheSize =10*1024*1024;
mClient.cache(newCache(externalCacheDir.getAbsoluteFile(),cacheSize));
}
设置超时时间:
mClient.connectTimeout(20,TimeUnit.SECONDS);
mClient.readTimeout(20,TimeUnit.SECONDS);
mClient.writeTimeout(20,TimeUnit.SECONDS);
设置请求头:
finalRequest request =newRequest.Builder().url("http://www.baidu.com")
.header("User-Agent","OkHttp Headers.java")
.addHeader("Accept","application/json; q=0.5")
.addHeader("Accept","application/vnd.github.v3+json")
.build();
返回数据处理:
用Gson就可以啦 😄
okhttp3 取消请求:
如果一个okhttp3网络请求已经不再需要,可以使用Call.cancel()来终止正在准备的同步/异步请求。如果一个线程正在写一个请求或是读取返回的response,它将会接收到一个IOException。
注意:
所有HTTP请求的代理设置,超时,缓存设置等都需要在OkHttpClient中设置。如果需要更改一个请求的配置,可以使用 OkHttpClient.newBuilder()获取一个builder对象,该builder对象与原来OkHttpClient共享相同的连接池,配置等。okhttp3 会自动重试未验证的请求。当一个请求返回401 Not Authorized时,需要提供Anthenticator,也支持代理,cookie。