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> T getService(Class<T> 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<ResponseBody> getMonthPrice(@Body MonthPriceParamsBean monthPriceParamsBean); @POST("PriceInfo/PriceInfoList") Call<ResponseBody> 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<ResponseBody>() { @Override public void onResponse(retrofit2.Call<ResponseBody> call, retrofit2.Response<ResponseBody> response) { String json = null; try { json = response.body().string(); ResultsBean<PriceInfoBean> result = mGson.fromJson(json, new TypeToken<ResultsBean<PriceInfoBean>>() { }.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<ResponseBody> call, Throwable t) { } });
打完收工。