环境:Android Studio 2020.3.1 patch 4
JDK版本 11.0.11
SDK版本 API 32 最小 21
Gradle版本 gradle-7.0.2

首先导入Okhttp包
在项目的build.gradle中的dependencies内添加

implementation("com.squareup.okhttp3:okhttp:4.9.3")

之后重新与gradle同步即可完成导入

在AndroidManifest中添加网络权限与允许明文传输

<uses-permission android:name="android.permission.INTERNET" />

自Android9.0系统开始,应用程序默认只允许使用HTTPS类型的网络请求,HTTP类型的网络请求因为有安全隐患默认不再支持。为了让应用程序支持HTTP请求,我们需要在AndroidManifest文件中的application块中添加

android:usesCleartextTraffic="true"

然后就可以开始封装啦
在项目中创建OkHttpUtils类
image
先封装get请求 代码如下

    public static void getRequest(String url,Callback callback){
    OkHttpClient client = new OkHttpClient();
    Request request = new Request.Builder()
            .url(url)
            .get()
            .build();
    client.newCall(request).enqueue(callback);
}

创建一个静态方法getRequest,传入两个形参,然后构建Okhttp包内封装的OkHttpClient构造方法,传入必要参数。
enqueue方法是异步传输 execute方法是同步传输
调用时的代码

    private void getRequest(){
    String url ="要请求的URL地址";
    OkhttpUtils.getRequest(url, new Callback() {
        @Override
        public void onFailure(@NonNull Call call, @NonNull IOException e) {
            Looper.prepare();
            Toast.makeText(MainActivity.this, "network error", Toast.LENGTH_SHORT).show();
            Log.i("Fail", "onFailure: " + e.getMessage());
        }

        @Override
        public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                    Log.i("Succeed", "onResponse: "+response.body().string());

        }
    });
}

Post请求

    public static void postRequest(String url,FormBody.Builder builder,Callback callback){
    OkHttpClient client = new OkHttpClient();
    FormBody body =builder.build();
    Request request = new Request.Builder()
            .url(url)
            .post(body)
            .build();
    client.newCall(request).enqueue(callback);
}

和get方法的区别就是增加了一个Builder对象用于向服务器提交数据,不指定类型默认为键值对
调用时的代码

            private void postRequest() {
            String url = "要请求的URL地址";
            FormBody.Builder builder = new FormBody.Builder()
                    .add("name", "value")
                    .add("name", "value"); //键值对类型的值
            OKhttp.postRequest(url, builder, new Callback() {
                @Override
                public void onFailure(@NonNull Call call, @NonNull IOException e) {
                    Log.i("11111", "onFailure: " + e.getMessage());
                }

                @Override
                public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                    Log.i("44444", "onResponse: " + Objects.requireNonNull(response.body()).string());
                }
            });
        }

如果要提交JSON类型的数据,则修改Post请求的封装为

    public static void postjsonRequest(String url,String json,Callback callback){
    OkHttpClient client = new OkHttpClient();
    RequestBody requestBody = FormBody.create(MediaType.parse("application/json; charset=utf-8"),json);
    Request request =new Request.Builder()
            .url(url)
            .post(requestBody)
            .build();
    client.newCall(request).enqueue(callback);

}

调用时代码为

            private void jsonRequest() {
            MediaType JSON = MediaType.parse("application/json;charset=utf-8");
            String url = "要请求的URL";
            JSONObject json = new JSONObject();
            try {
                json.put("name", "value")
                        .put("name", "value"); //json类型的参数
            } catch (JSONException e) {
                e.printStackTrace();
            }

            OKhttp.postjsonRequest(url, String.valueOf(json), new Callback() {
                @Override
                public void onFailure(@NonNull Call call, @NonNull IOException e) {
                    Log.i("11111", "onFailure: " + e.getMessage());
                }

                @Override
                public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                    Log.i("222222", "onResponse: " + Objects.requireNonNull(response.body()).string());
                }
            });
        }

使用时调用构建出的方法即可