retrofit2网络使用方法


1、导入包

 //retrofit2类
    implementation 'com.squareup.retrofit2:retrofit:2.9.0'
    implementation 'com.squareup.retrofit2:converter-gson:2.9.0'

2、网络权限等,可以看前面的。

3、建立公用的retrofit操作类

public class RetrofitClient {
    public static final String BaseUrl = "http://XXXXXX/api/";
    private static volatile RetrofitClient mInstance;
    private  Retrofit retrofit;

    public static RetrofitClient getInstance(){
        if(mInstance==null){
            synchronized(RetrofitClient.class) {
                if (mInstance == null) {
                    mInstance = new RetrofitClient();
                }
            }
        }
        return mInstance;
    }

    public  T getService(Class cls){
        return getRetrofit().create(cls);
    }

    private synchronized Retrofit getRetrofit(){
        if(retrofit==null) {
            retrofit = new Retrofit.Builder().baseUrl(BaseUrl)
                    .addConverterFactory(GsonConverterFactory.create())
                    .build();
        }
        return retrofit;
    }
}

4、新建Service类

import Beans.MonthPriceParamsBean;
import Beans.PriceInfoListParamsBean;
import okhttp3.ResponseBody;
import retrofit2.http.Body;
import retrofit2.http.POST;
import retrofit2.Call;

public interface IPriceService {
    @POST("PriceInfo/MonthPrice")
    Call getMonthPrice(@Body MonthPriceParamsBean monthPriceParamsBean);

    @POST("PriceInfo/PriceInfoList")
    Call getPriceList(@Body PriceInfoListParamsBean priceInfoListParamsBean);
}

5、调用

priceService =  RetrofitClient.getInstance().getService(IPriceService.class);
PriceInfoListParamsBean priceInfoListParamsBean = new PriceInfoListParamsBean("admin", -1, -1, -1);

        call = priceService.getPriceList(priceInfoListParamsBean);
        call.enqueue(new retrofit2.Callback() {
            @Override
            public void onResponse(retrofit2.Call call, retrofit2.Response response) {
                String json = null;
                try {
                    json = response.body().string();
                    ResultsBean result = mGson.fromJson(json, new TypeToken>() {
                    }.getType());
                    if (result.getSuccess()) {
                        getActivity().runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                jlListAdapter.setList(result.getResults());
                            }
                        });
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(retrofit2.Call call, Throwable t) {

            }
        });

打完收工。