说明
OKHttp3 主要是一个网络请求
- 网络请求方式一般为PUT,DELETE,POST,GET等。常用的是get、post
- 文件的上传下载
- 加载图片(内部会图片大小自动压缩)
- 支持请求回调,直接返回对象、对象集合
- 支持session的保持
示例
1、添加依赖库、和网络权限
- 依赖库
build.gradle
// okhttp3 的依赖库
implementation 'com.squareup.okhttp3:okhttp:4.9.0'
网络权限
AndroidManifest.xml
<uses-permission android:name="android.permission.INTERNET"/>
2、布局文件
主要用于示例中按钮处方请求
res/layout/activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<Button
android:id="@+id/btn_mian_one"
android:text="Get同步请求"
android:onClick="GetSyn"
android:layout_width="200dp"
android:layout_height="50dp"
/>
<Button
android:id="@+id/btn_mian_two"
android:text="Get异步请求"
android:onClick="GetAsync"
android:layout_width="200dp"
android:layout_height="50dp"
/>
<Button
android:id="@+id/btn_mian_three"
android:text="Post同步请求"
android:onClick="PostSyn"
android:layout_width="200dp"
android:layout_height="50dp"
/>
<Button
android:id="@+id/btn_mian_four"
android:text="post异步请求"
android:onClick="PostAsync"
android:layout_width="200dp"
android:layout_height="50dp"
/>
</LinearLayout>
网络请求
1、公共
主要各种请求提取相同代码
定义 okHttpClient
private OkHttpClient okHttpClient;
实例化
okHttpClient = new OkHttpClient();
2、Get同步请求
// get 同步步请求
public void GetSyn(View view) {
Request request = new Request.Builder().url("https://www.baidu.com/s?wd=12").build();
Call call = okHttpClient.newCall(request);
new Thread(new Runnable() {
@Override
public void run() {
try {
Response response = call.execute();
Log.e(TAG, "GetSyn: " +response.body().string());
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
}
**3、Get异步请求 **
// get 异步请求
public void GetAsync(View view) {
Request request = new Request.Builder().url("https://www.baidu.com/s?wd=12").build();
Call call = okHttpClient.newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(@NonNull Call call, @NonNull IOException e) {
Log.e(TAG, "GetAsync: " +e);
}
@Override
public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
Log.e(TAG, "GetAsync: " +response.body().string());
}
});
}
备注1
Get的同步、异步大部分很相似。
1、第一步都是-创建OkHttpClient对象(公共中创建的)
2、第二步都是-通过Request.Builder来创建Request对象
3、第三步都是-创将抽象Call 执行请求的对象
Request request = new Request.Builder().url("https://www.baidu.com/s?wd=12").build();
Call call = okHttpClient.newCall(request);
区别在于
4、第四步的区别:
同步:用call.execute();执行,并用Response接收响应
异步:call.enqueue()
5、注意问题:同步代码一般单开线程,避免时间过程
备注2
- Reques:该t对象是http请求的抽象对象(包括请求地址,请求方法,请求头,请求体等内容)。通常用Request.Builder来创建该对象。通过request对象的url,method,headers,body等方法能够获取到请求的对应信息。
- Response对象是http响应的抽象对象(包括响应头,响应体等内容)。
- Call对象抽象的是一个正在准备执行的请求
Post 同步请求
// post 同步请求
public void PostSyn(View view) {
FormBody formBody = new FormBody.Builder().add("wd","12")
.build();
Request request = new Request.Builder().url("https://www.baidu.com/s").post(formBody).build();
Call call = okHttpClient.newCall(request);
new Thread(){
@Override
public void run() {
try {
Response response = call.execute();
Log.e(TAG, "PostAsync: " +response.body().string());
} catch (IOException e) {
e.printStackTrace();
}
}
}.start();
}
Post 异步请求
// post 异步请求
public void PostAsync(View view) {
FormBody formBody = new FormBody.Builder().add("wd","12")
.build();
Request request = new Request.Builder().url("https://www.baidu.com/s").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.e(TAG, "PostAsync: "+response.body().string());
}
});
备注3
Post 的同步和异步相差不多,同“备注1”
备注4
get 和post的同步代码也很相似
区别主要在于post 需要通过FormBody.Builder()创建表单参数。然后才可以传给Request。
其他的步骤基本相似
同理,get 和post的异步代码一样
最终代码java/com/pha/four/MainActivity.java
package com.pha.four;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import java.io.IOException;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
public class MainActivity extends AppCompatActivity {
private static final String TAG = "MainActivity";
private OkHttpClient okHttpClient;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
okHttpClient = new OkHttpClient();
}
// get 同步步请求
public void GetSyn(View view) {
Request request = new Request.Builder().url("https://www.baidu.com/s?wd=12")
.build();
Call call = okHttpClient.newCall(request);
new Thread(new Runnable() {
@Override
public void run() {
try {
Response response = call.execute();
Log.e(TAG, "GetSyn: " +response.body().string());
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
}
// get 异步请求
public void GetAsync(View view) {
Request request = new Request.Builder().url("https://www.baidu.com/s?wd=12").build();
Call call = okHttpClient.newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(@NonNull Call call, @NonNull IOException e) {
Log.e(TAG, "GetAsync: " +e);
}
@Override
public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
Log.e(TAG, "GetAsync: " +response.body().string());
}
});
}
// post 同步请求
public void PostSyn(View view) {
FormBody formBody = new FormBody.Builder().add("wd","12")
.build();
Request request = new Request.Builder().url("https://www.baidu.com/s").post(formBody).build();
Call call = okHttpClient.newCall(request);
new Thread(){
@Override
public void run() {
try {
Response response = call.execute();
Log.e(TAG, "PostAsync: " +response.body().string());
} catch (IOException e) {
e.printStackTrace();
}
}
}.start();
}
// post 异步请求
public void PostAsync(View view) {
FormBody formBody = new FormBody.Builder().add("wd","12")
.build();
Request request = new Request.Builder().url("https://www.baidu.com/s").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.e(TAG, "PostAsync: "+response.body().string());
}
});
}
}