AndroidApp/RetrofitClient.java

38 lines
1.5 KiB
Java
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package com.example.myapplication.Tool;
import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
import java.util.concurrent.TimeUnit;
public class RetrofitClient {
private static final String BASE_URL = "http://pms.dtyx.net:9158/";
private static Retrofit retrofit;
public static Retrofit getClient(String authToken) {
if (retrofit == null) {
// 创建 OkHttpClient 并添加拦截器
OkHttpClient.Builder okHttpClientBuilder = new OkHttpClient.Builder()
.connectTimeout(30, TimeUnit.SECONDS)
.readTimeout(30, TimeUnit.SECONDS)
.writeTimeout(30, TimeUnit.SECONDS);
// 添加日志拦截器(可选)
HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BASIC);
okHttpClientBuilder.addInterceptor(loggingInterceptor);
// 添加认证拦截器(自动添加 Authorization header
okHttpClientBuilder.addInterceptor(new AuthInterceptor(authToken));
// 构建 Retrofit
retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.client(okHttpClientBuilder.build())
.addConverterFactory(GsonConverterFactory.create())
.build();
}
return retrofit;
}
}