最近学习网络框架的封装,在常用的代码中基本上都是添加相应的依赖包,使用的第三方,方便快捷,但是对技术的深入学习是不可避免的,今天学习一下Retrofit的简易封装.在此贴出来,以后方便使用.
首先建一个RetrofitHelper.java
代码如下:
package com.yiju.leal.net; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.yiju.leal.App; import com.yiju.leal.LealApplication; import com.yiju.leal.entity.Login; import com.yiju.leal.entity.OrderDetail; import com.yiju.leal.net.cookie.CookieManger; import com.yiju.leal.net.interceptor.LoggingInterceptor; import java.util.ArrayList; import java.util.concurrent.TimeUnit; import okhttp3.OkHttpClient; import retrofit2.Call; import retrofit2.Retrofit; import retrofit2.converter.gson.GsonConverterFactory; /** * Created by song on 2017/3/30 11:03 */ public class RetrofitHelper { private static final int DEFAULT_TIMEOUT = 10; private static RetrofitHelper mRetrofitHelper; private ApiService mApiService; private Retrofit retrofit; private static Gson gson; public static RetrofitHelper getInstance(){ if(mRetrofitHelper==null) { synchronized (RetrofitHelper.class) { mRetrofitHelper = new RetrofitHelper(); gson = new GsonBuilder() .setDateFormat("yyyy-MM-dd HH:mm:ss") .create(); } } return mRetrofitHelper; } private <T> T configRetrofit(Class<T> service,String baseUrl){ retrofit = new Retrofit .Builder() .baseUrl(App.BASE_URL) .addConverterFactory(GsonConverterFactory.create()) .client(getSimpleClient()) .build(); return (T) retrofit.create(ApiService.class); } private OkHttpClient.Builder getBuilder() { OkHttpClient.Builder builder = new OkHttpClient.Builder() .readTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS) .writeTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS) .connectTimeout(12, TimeUnit.SECONDS) .retryOnConnectionFailure(true) // .cookieJar(new CookieManger(LealApplication.application.getApplicationContext()))//暂时不添加cookie .addInterceptor(new LoggingInterceptor());//添加日志拦截器 //TODO 添加缓存的拦截器 return builder; } public OkHttpClient getSimpleClient() { return getBuilder().build(); } public ApiService getApi(){ return mApiService == null ? configRetrofit(ApiService.class,App.BASE_URL):mApiService; } } 上面的类中暴露了一个getApi进行使用,在此return一个mApiService.
ApiService:
package com.yiju.leal.net; import com.yiju.leal.entity.AddCertificationEntity; import com.yiju.leal.entity.AddCommentEntity; import com.yiju.leal.entity.AppUserInfoEntity; import com.yiju.leal.entity.ClassDetail; import com.yiju.leal.entity.DrivingDetail; import com.yiju.leal.entity.EnrollEntity; import com.yiju.leal.entity.Login; import com.yiju.leal.entity.MoreSchool; import com.yiju.leal.entity.Order; import com.yiju.leal.entity.OrderDetail; import com.yiju.leal.entity.OrderEntity; import com.yiju.leal.entity.ReCommendEntity; import com.yiju.leal.entity.ResponEntity; import com.yiju.leal.entity.ReviseHeadImgEntity; import com.yiju.leal.entity.SelectCommentEntity; import com.yiju.leal.entity.UserCertification; import java.util.ArrayList; import java.util.List; import retrofit2.Call; import retrofit2.http.Field; import retrofit2.http.FormUrlEncoded; import retrofit2.http.GET; import retrofit2.http.POST; import retrofit2.http.Path; import retrofit2.http.Query; /** * Created by song on 2017/3/30 11:30 */ public interface ApiService { //TODO retrofit接口方法 /** * 登录接口 * @param * @param phone * @return */ @FormUrlEncoded @POST("api/v1/login/login") Call<Login> login(@Field("requestType") String requestType, @Field("verificationCode") String verificationCode, @Field("phoneNumber") String phone); /** * 发送验证码接口 * @param requestType * @param phoneNumber * @return */ @FormUrlEncoded @POST("api/v1/login/sendVerificationCode") Call<Login> getVerificationCode( @Field("requestType") String requestType, @Field("phoneNumber")String phoneNumber); /** * 退出登录 * @param requestType * @param phoneNumber * @return */ @GET("api/v1/login/logout") Call<Login>logout( @Query("requestType") String requestType, @Query("phoneNumber") String phoneNumber, @Query("token")String token); /** * 报名接口 * @param requestType * @param appUserId * @param schoolId * @param classId * @return */ @FormUrlEncoded @POST("api/v1/classorder/enroll") Call<EnrollEntity> signUp( @Field("requestType") String requestType, @Field("appUserId")int appUserId, @Field("schoolId")int schoolId, @Field("classId")int classId); /** * 提交实名认证 * @param requestType * @param appUserId * @param sex * @param appUserTrueName * @param address * @param idCard * @param phoneNumber * @param ImgFront * @param ImgOpposite * @return */ @FormUrlEncoded @POST("api/v1/appuser/addCertification") Call<AddCertificationEntity> addCertification( @Field("requestType") String requestType, @Field("appUserId")Integer appUserId, @Field("sex")Integer sex, @Field("appUserTrueName")String appUserTrueName, @Field("address")String address, @Field("idCard")String idCard, @Field("phoneNumber")String phoneNumber, @Field("ImgFront")String ImgFront, @Field("ImgOpposite")String ImgOpposite); /** * 获取用户信息接口 * @param appUserId * @param requestType * @return */ @GET("api/v1/appuser/{appUserId}") Call<AppUserInfoEntity> getUserInfo(@Path("appUserId")Integer appUserId, @Query("requestType")String requestType); /** * 修改头像 * @param appUserId * @param headImgName * @return */ @FormUrlEncoded @POST("api/v1/appuser/ {appUserId}/headImg") Call<ReviseHeadImgEntity>headImg(@Path("appUserId") int appUserId, @Field("headImgName")String headImgName, @Field("requestType")String requestType); /** * 修改名称 * @param requestType * @param appUserId * @param nickname * @return */ @FormUrlEncoded @POST("api/v1/appuser/{appUserId}/nickName") Call<ResponEntity>reviseNickName(@Field("requestType")String requestType, @Path("appUserId") int appUserId, @Field("nickname")String nickname); /** * 我的订单接口 * @param appUserId * @param orderState * @param requestType * @return */ @GET("api/v1/classorder/allOrder") Call<Order>getOrder(@Query("appUserId") int appUserId, @Query("orderState") int orderState, @Query("requestType") String requestType); /** * 获取订单详情 * @param requestType * @param orderId * @return */ @GET("api/v1/classorder/{orderId}") Call<OrderDetail> getOrder(@Query("requestType")String requestType, @Path("orderId")String orderId); /** * 添加评论的接口 * @param requestType * @param orderId * @param schoolId * @param appUserId * @param content * @param score * @return */ @FormUrlEncoded @POST("api/v1/comment/addComment") Call<AddCommentEntity> addComment(@Field("requestType")String requestType, @Field("orderId")String orderId, @Field("schoolId")int schoolId, @Field("appUserId")int appUserId, @Field("content")String content, @Field("score")Float score); /** * 根据订单查询评论接口 * @param requestType * @param orderId * @return */ @GET("api/v1/comment/{orderId}") Call<SelectCommentEntity> selectComment(@Query("requestType")String requestType, @Path("orderId") String orderId); /** * 获取用户认证状态 * @param requestType * @param appUserId * @return */ @GET("api/v1/appuser/{appUserId}/trueCertification") Call<UserCertification> certification( @Path("appUserId") int appUserId, @Query("requestType")String requestType); /** * 推荐驾校接口 * @param cityId * @param longitude * @param latitude * @param requestType * @return */ @GET("api/v1/schools/recommend") Call<List<ReCommendEntity>>recommend(@Query("cityId")int cityId, @Query("longitude")String longitude, @Query("latitude")String latitude, @Query("requestType")String requestType); /** * 更多驾校接口 * @param requestType * @param cityId * @param areaId * @param sortType * @param filter * @param longitude * @param latitude * @param page * @return */ @GET("api/v1/schools/more") Call<List<MoreSchool>>moreSchool(@Query("requestType")String requestType, @Query("cityId")int cityId, @Query("areaId")int areaId, @Query("sortType")String sortType, @Query("filter")int filter, @Query("longitude")String longitude, @Query("latitude")String latitude, @Query("page")int page); /** * 驾校详情接口 * @param requestType * @param schoolId * @return */ @GET("api/v1/schools/{schoolId}") Call<DrivingDetail> driverDetail( @Path("schoolId") int schoolId, @Query("requestType")String requestType); /** * 班级详情接口: * @param classId * @param requestType * @return */ @GET("api/v1/classes/{classId}") Call<ClassDetail> classDetail(@Path("classId")int classId, @Query("requestType")String requestType); /** * 分期付款接口 * @param requestType * @param orderId * @param name * @param phone * @param userId * @return */ @FormUrlEncoded @POST("api/v1/installments") Call<ResponEntity> installments(@Field("requestType") String requestType, @Field("orderId") String orderId, @Field("name") String name, @Field("phone") String phone, @Field("userId") int userId); @FormUrlEncoded @POST("api/v1/feedback/addFeedback") Call<ResponEntity> addFeedback(@Field("appUserId")int appUserId, @Field("comment") String comment, @Field("requestType") String requestType); } 所以在其中牵涉到请求,就可以直接进行调用即可,方便快捷,减少了代码量
eg:
/** * 登录 * @param requestType * @param verificationCode * @param phoneNum */ private void getlogin(String requestType,String verificationCode, final String phoneNum){ loginCall = RetrofitHelper.getInstance().getApi().login(requestType,verificationCode, phoneNum); loginCall.enqueue(new Callback<Login>() { @Override public void onResponse(Call<Login> call, Response<Login> response) { Login login=response.body(); if(login!=null&&login.getResult().equals("RESULT_SUCCESS")){ Log.d(TAG,"LoginResult:"+login.getResult().equals("RESULT_SUCCESS")); //登录成功 User user = new User(); user.setPhone(phoneNum); user.setToken(login.getToken()); user.setId(login.getId()); user.setNickname(phoneNum); SharedPreUtils.getInstance(LoginActivity.this).saveUser(JSON.toJSONString(user)); EventBus.getDefault().post(new UpDateEvent(phoneNum)); finish(); }else{ //登录失败 Toast.makeText(LoginActivity.this,"验证码不正确",Toast.LENGTH_LONG).show(); } } @Override public void onFailure(Call<Login> call, Throwable t) { } }); }