HttpUtils.java 2.0 KB
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;
    }

}