compile 'com.squareup.okhttp3:okhttp:3.4.2'
public class MainActivity extends Activity {
private String tag = "MainActivity";
private Context mContext;
private OkHttpClient client;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mContext = this;
initData();
}
private void initData() {
client = getOkHttpClient();
// 同步Get请求
//getRequest();
// 异步Get请求
getAsyncRequest();
}
private OkHttpClient getOkHttpClient() {
// 设置缓存
Cache cache = new Cache(mContext.getCacheDir(), 1024 * 1024 * 10);
OkHttpClient client = new OkHttpClient.Builder()
.cache(cache)
.connectTimeout(20, TimeUnit.SECONDS)
.readTimeout(20, TimeUnit.SECONDS)
.build();
return client;
}
private void getRequest() {
new Thread() {
@Override
public void run() {
String url = "http://www.baidu.com";
Request request = new Request.Builder().url(url).build();
try {
// execute为同步请求,所以这里放在了Thread里。
Response response = client.newCall(request).execute();
if (response.isSuccessful()) {
String result;
if (response.cacheResponse() == null) {
result = response.body().string();
} else {
result = response.body().string();
}
Log.i(tag, result);
} else {
Log.i(tag, "request failure");
}
} catch (IOException e) {
e.printStackTrace();
}
}
}.start();
}
private void getAsyncRequest() {
String url = "http://www.baidu.com";
Request request = new Request.Builder().url(url).build();
// enqueue 加入调度,onResponse在工作线程执行
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
Log.i(tag, "onFailure");
}
@Override
public void onResponse(Call call, Response response) throws IOException {
if(response.isSuccessful()){
String result;
if (response.cacheResponse() == null) {
result = response.body().string();
} else {
result = response.body().string();
}
Log.i(tag, result);
}
}
});
}
}