Retrofit的通讯方式示例


Retrofit有两种通讯方式,同步和异步

异步方式:

 APIService req;
        req = RetrofitManager.getInstance().createReq(APIService.class);
        String deviceId=DeviceUtil.GetDeviceId(context);
        Call res= req.getCpDatas(GetBaoCanReqPara(deviceId,fromId));
        res.enqueue(new Callback() {
            @Override
            public void onResponse(Call call, Response response) {
                Log.e("", "");
                try {

同步方式:

APIService req;
req = RetrofitManager.getInstance().createReq(APIService.class);
try{
       Call res= req.CheckSignState(hashMap);
       final Response execute = res.execute();
       String json=execute.body().string();

封装类库:

import java.util.concurrent.TimeUnit;

import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.GsonConverterFactory;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;

public class RetrofitManager {
    private static RetrofitManager mRetrofitManager;
    private Retrofit mRetrofit;

    private RetrofitManager(){
        initRetrofit();
    }

    public static synchronized RetrofitManager getInstance(){
        if (mRetrofitManager == null){
            mRetrofitManager = new RetrofitManager();
        }
        return mRetrofitManager;
    }


    private void initRetrofit() {
        HttpLoggingInterceptor LoginInterceptor = new HttpLoggingInterceptor();
        LoginInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
        OkHttpClient.Builder builder = new OkHttpClient.Builder();


        if (AppConfig.DEBUG){
            builder.addInterceptor(LoginInterceptor); //添加retrofit日志打印
        }


        builder.connectTimeout(15, TimeUnit.SECONDS);
        builder.readTimeout(20, TimeUnit.SECONDS);
        builder.writeTimeout(20, TimeUnit.SECONDS);
        builder.retryOnConnectionFailure(true);
        OkHttpClient client = builder.build();

        mRetrofit = new Retrofit.Builder()
                .baseUrl(AppConfig.BASE_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())//用于返回Rxjava调用,非必须
                .client(client)
                .build();
    }

    public  T createReq(Class reqServer){
        return mRetrofit.create(reqServer);
    }
}