初探OkHttp3

42次阅读

共计 2308 个字符,预计需要花费 6 分钟才能阅读完成。

在应用开发中肯定会用到网络请求,下面让我们一起了解 OkHttp3 这个网络请求框架吧。
项目中引用
Module 的 build.gradle 文件中引入:
dependencies {
compile ‘com.squareup.okhttp3:okhttp:3.12.1’
}
异步 Get 请求
OkHttpClient 是连接对象,无论是什么请求,使用 OKHttp 都必须要创建这个对象。Request 是请求对象的参数,里面需要放置各种请求信息。enqueue() 是使用异步请求方法。
OkHttpClient client = new OkHttpClient();
private void okhttpAsyncGet(){
Request request = new Request.Builder()
.url(“https://api.apiopen.top/getJoke?page=1&count=2&type=video”)
.build();

client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {

}

@Override
public void onResponse(Call call, Response response) throws IOException {
Log.e(“error”,response.body().string());
}
});
}
异步 Post 请求
这里我们使用 Post 请求,和上面 Get 请求用的 URL 是一样的。不同的是用 Post 请求需要使用 RequestBody 这个对象,用 add() 方法,添加我们的请求参数。
private void okhttpAsyncPost(){
RequestBody formBody = new FormBody.Builder()
.add(“page”, “1”)
.add(“count”, “2”)
.add(“type”,”video”)
.build();
Request request = new Request.Builder()
.url(“https://api.apiopen.top/getJoke”)
.post(formBody)
.build();

client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {

}

@Override
public void onResponse(Call call, Response response) throws IOException {
Log.e(“error”,response.body().string());
}
});
}
同步请求
同步请求的话,在 Android 开发中不是很常用,在主线程中是不能进行网络请求的所以我们这个要开一个子线程进行同步请求。使用同步请求的是需要调用 execute() 方法,Response 接收返回的对象。同步和异步请求只是最后一步的请求的方法不同而已。
private Runnable runnable;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_okhttp);
okhttpPost();
new Thread(runnable).start();
}
private void okhttpPost() {
runnable = new Runnable(){
@Override
public void run() {
try {

RequestBody formBody = new FormBody.Builder()
.add(“page”, “1”)
.add(“count”, “2”)
.add(“type”,”video”)
.build();

Request request = new Request.Builder()
.url(“https://api.apiopen.top/getJoke”)
.post(formBody)
.build();
Response response = client.newCall(request).execute();
Log.e(“error”,response.body().string());
} catch (Exception e) {
Toast.makeText(OkhttpActivity.this,” 异常 ”,Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
}
};
}
响应超时设置
当请求服务器没有反应时,这里我们可以通过 OkHttpClient 对象来设置请求响应超时。
OkHttpClient client = new OkHttpClient()
.newBuilder()
.connectTimeout(60, TimeUnit.SECONDS)
.writeTimeout(60, TimeUnit.SECONDS)
.readTimeout(60, TimeUnit.SECONDS)
.build();
上面的 URL 都是可以使用测试的。Ok,这样我们就可以简单快速上手 OKHttp3 了,后面会继续讲解 OKHttp3 的一些高级用法。
最近我会写很多关于 Android 常用控件的使用,里面都是一些很有用的知识,如果你感觉有用,请给我一个 star, 谢谢。代码实例

正文完
 0