什么是OkHttp
OKHttp是由Square公司贡献的一个处理网络请求的开源项目,是目前Android使用最广泛的网络框架。从Android4.4开始HttpURLConnection的底层实现采用的是OKHttp。
提示:以下是本篇文章正文内容,下面案例可供参考
一、OkHttp的优势
1.支持HTTP/2,允许所有同一个主机地址的请求共享同一个socket连接
2.连接池减少请求延时
3.透明的GZIP压缩减少响应数据的大小
4.缓存响应内容,避免一些完全重复的请求
二、使用步骤
1.添加依赖并打开网络权限
1.在build.gradle中添加依赖
implementation("com.squareup.okhttp3:okhttp:4.9.0")
2.在AndroidManifest.xml文件打开网络权限
<uses-permission android:name="android.permission.INTERNET" />
2.OkHttp基本用法
1.OkHttp分为同步请求和异步请求。
同步请求会在请求的时候阻塞进程,直到请求结束才执行后序代码。而异步请求会进行监听,当请求完成时,通过回调通知请求的结果,不会影响后序代码的执行。
2.OkHttp的请求方式由Get、Post、Put等。使用最多的就是Get和Post。本文将了解Get和Post的同步请求和异步请求操作。默认使用Get请求。
三、代码展示
1.布局文件
1.首先进行布局文件的设置。
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<Button
android:id="@+id/GetTong"
android:text="Get同步请求"
android:textSize="30sp"
android:textAllCaps="false"
android:onClick="GetSync"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
<Button
android:id="@+id/PostTong"
android:text="Post同步请求"
android:textSize="30sp"
android:textAllCaps="false"
android:onClick="PostSync"
android:layout_marginTop="20dp"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
<Button
android:id="@+id/GetYi"
android:text="Get异步请求"
android:textSize="30sp"
android:textAllCaps="false"
android:onClick="GetAsync"
android:layout_marginTop="20dp"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
<Button
android:id="@+id/PostYi"
android:text="Post异步请求"
android:textSize="30sp"
android:textAllCaps="false"
android:onClick="PostAsync"
android:layout_marginTop="20dp"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</LinearLayout>
布局视图如下:
2.创建OkhttpClient的实例对象。
(以下代码都在主Activity中操作)
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_ok_http);
okhttpClient = new OkHttpClient();//创建OkhttpClient的实例对象
}
//以下代码后序操作补充
public void GetSync(View view) {//Get同步请求
}
public void PostSync(View view) {//Post同步请求
}
public void PostAsync(View view) {//Post异步请求
}
public void GetAsync(View view) {//Get异步请求
}
}
2.Get的同步请求
public void GetSync(View view) {
new Thread(){//在子线程中进行网络请求
@Override
public void run() {
Request request = new Request.Builder().url("https://www.httpbin.org/get?a=1&b=2").build();
//get表示请求方式;?a=1&b=2表示传递的参数(可加可不加)
Call call = okhttpClient.newCall(request);
//准备好请求的call对象
try {
Response response = call.execute();//响应
Log.i("yxy", "getSync': "+response.body().string());
//body()得到响应的响应体。
} catch (IOException e) {
e.printStackTrace();
}
}
}.start();
}
3.Get的异步请求
异步请求不需要用户主动创建线程。
public void GetAsync(View view) {
Request request = new Request.Builder().url("https://www.httpbin.org/get?a=1&b=2").build();
Call call = okhttpClient.newCall(request);
call.enqueue(new Callback() {//异步请求,需要传递回调对象,重写方法
@Override
public void onFailure(@NonNull Call call, @NonNull IOException e) { }
@Override
public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
if (response.isSuccessful()){
Log.i("yxy", "getAsync: "+response.body().string());
}
}
});
}
4.Post的同步请求
public void PostSync(View view) {
new Thread(){
@Override
public void run() {
FormBody formBody = new FormBody.Builder().add("a","1").add("b","2").build();
//请求体,将参数加在请求体当中
Request request = new Request.Builder().url("\"https://www.httpbin.org/post").post(formBody).build();
Call call = okhttpClient.newCall(request);
Response response = null;
try {
response = call.execute();
Log.i("yyy", "PostSync: "+response.body().string());
} catch (IOException e) {
e.printStackTrace();
}
}
}.start();
}
5.Post的异步请求
public void PostAsync(View view) {
FormBody formBody = new FormBody.Builder().add("a","1").add("b","2").build();
//请求体,将参数加在请求体当中
Request request = new Request.Builder().url("\"https://www.httpbin.org/post").post(formBody).build();
Call call = okhttpClient.newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(@NonNull Call call, @NonNull IOException e) {
}
@Override
public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
Log.i("yyy", "PostAsync: "+response.body().string());
}
});
}