You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

79 lines
2.5 KiB
Java

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

package com.rehome.dywoa.utils;
import android.content.Context;
import android.util.Log;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
public class OkhttpUtils {
private static OkhttpUtils instance = null;
private static Context context;
public static OkhttpUtils getInstance(Context context) {
if (instance == null) {
instance = new OkhttpUtils(context);
}
return instance;
}
private OkhttpUtils(Context context) {
OkhttpUtils.context = context;
}
public OkHttpClient getOkHttpClient() {
OkHttpClient.Builder httpClientBuilder = new OkHttpClient
.Builder();
//OkHttp进行添加拦截器loggingInterceptor
httpClientBuilder.addInterceptor(new LoggingInterceptor());
//设置超时时间
httpClientBuilder.connectTimeout(60, TimeUnit.SECONDS);
httpClientBuilder.writeTimeout(60, TimeUnit.SECONDS);
httpClientBuilder.readTimeout(60, TimeUnit.SECONDS);
return httpClientBuilder.build();
}
public static class LoggingInterceptor implements Interceptor {
@Override
public Response intercept(Chain chain) throws IOException {
//这个chain里面包含了request和response所以你要什么都可以从这里拿
Request request = chain.request();
long t1 = System.nanoTime();//请求发起的时间
Log.d("okhttpmsg", String.format("发送请求 %s on %s%n%s",
request.url(), chain.connection(), request.headers()));
Response response = chain.proceed(request);
long t2 = System.nanoTime();//收到响应的时间
//这里不能直接使用response.body().string()的方式输出日志
//因为response.body().string()之后response中的流会被关闭程序会报错我们需要创建出一
//个新的response给应用层处理
ResponseBody responseBody = response.peekBody(1024 * 1024);
Log.d("okhttpmsg", String.format("接收响应: [%s] %n返回json:【%s】 %.1fms%n%s",
response.request().url(),
responseBody.string(),
(t2 - t1) / 1e6d,
response.headers()));
return response;
}
}
}