HttpUtils.java
2.0 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
package com.hh.xuetubao.Utils;
import android.util.Log;
import com.hh.xuetubao.MyApplication;
import com.hh.xuetubao.MyServer;
import java.io.File;
import java.util.concurrent.TimeUnit;
import okhttp3.Cache;
import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;
public class HttpUtils {
public static HttpUtils sHttpUtils;
public HttpUtils() {
}
public static HttpUtils getInstance() {
if (sHttpUtils == null) {
sHttpUtils = new HttpUtils();
}
return sHttpUtils;
}
public MyServer getServer(String url) {
return new Retrofit.Builder()
.baseUrl(url)
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.client(getClientWithoutCache())
.build()
.create(MyServer.class);
}
public OkHttpClient getClientWithoutCache() {
return new OkHttpClient.Builder()
.cache(new Cache(new File(MyApplication.getContext().getCacheDir(), "HttpCache"), 10 * 1024 * 1024))
.connectTimeout(6 * 1000, TimeUnit.SECONDS)
.readTimeout(6, TimeUnit.SECONDS)
.writeTimeout(6, TimeUnit.SECONDS)
.addInterceptor(getLogInterceptor())
.build();
}
public static HttpLoggingInterceptor getLogInterceptor() {
//设置log拦截器拦截内容
HttpLoggingInterceptor.Level level = HttpLoggingInterceptor.Level.BODY;
//新建log拦截器
HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() {
@Override
public void log(String message) {
Log.e("<--网络请求-->", message);
}
});
loggingInterceptor.setLevel(level);
return loggingInterceptor;
}
}