确保Android Studio版本为3.0或更高版本。
在build.gradle文件中添加依赖项: debugImplementation 'com.squareup.okhttp3:okhttp:3.14.4'
在AndroidManifest.xml文件中添加以下权限:
在代码中添加Network Inspector:
import okhttp3.OkHttpClient; import okhttp3.logging.HttpLoggingInterceptor; import java.util.concurrent.TimeUnit;
OkHttpClient.Builder builder = new OkHttpClient.Builder() .connectTimeout(30, TimeUnit.SECONDS) .readTimeout(30, TimeUnit.SECONDS);
if (BuildConfig.DEBUG) { HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor(); loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BASIC); builder.addInterceptor(loggingInterceptor); }
OkHttpClient client = builder.build(); client.dispatcher().setIdleCallback(() -> { // Add your custom logic to be executed every time the network is idle });
// Here's how you can use the client to make a request
client.newCall(request).enqueue(callback);
在Android Studio中运行应用程序并打开Network Inspector,查看网络交互。