1. 程式人生 > >常用網路框架

常用網路框架

API

public class API {
    public static boolean isOnline = false;
    public static final String DEV = "http://120.27.23.105/";
    public static final String WROK = "";
    public static final String HOST = isOnline ? WROK : DEV;

    public static final String LOGIN = "user/login";//登陸
public static final 
String REGISTER = "user/reg";//註冊 public static final String HOMEAD = "ad/getAd";//首頁廣告、輪播 public static final String PRODUCTDETAIL = "product/getProductDetail?source=android";//商品詳情 public static final String GETCARTS = "product/getCarts?source=android";//查詢購物車 public static final String ADDCART = "product/addCart?source=android"
;//新增購物車 }
ServiceApi
public interface ServiceApi {
    //登入
@GET(API.LOGIN)
    Observable<LoginBean> getLogin(@Query("mobile") String mobile, @Query("password") String password);

    //註冊
@GET(API.REGISTER)
    Observable<RegisterBean> getRegister(@Query("mobile") String mobile, @Query("password"
) String password); //首頁廣播 @GET(API.HOMEAD) Observable<ShouYeBean> getAD(); //商品詳情 @GET(API.PRODUCTDETAIL) Observable<ProductDetailBean> getDetail(@Query("pid") String pid); //新增購物車 @GET(API.ADDCART) Observable<AddCartBean> addCart(@Query("uid") String uid, @Query("pid") String pid); //查詢購物車 @GET(API.GETCARTS) Observable<ShopCartBean> getGoods(@Query("uid") String uid, @Query("token") String token); }
RetrofitHelper
public class RetrofitHelper {
    private static OkHttpClient okHttpClient;
    private static ServiceApi serviceApi;

    static {
        initOkHttpClient();
    }

    private static void initOkHttpClient() {
        if (okHttpClient == null) {
            synchronized (RetrofitHelper.class){
                if (okHttpClient == null) {
                    HttpLoggingInterceptor interceptor=new HttpLoggingInterceptor();
                    interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
                    okHttpClient=new OkHttpClient.Builder()
                            .addInterceptor(interceptor)
                            .build();
                }
            }
        }
    }

    //定義一個泛型方法
public static <T> T createAPI(Class<T> tClass, String url) {
        Retrofit retrofit=new Retrofit.Builder()
                .baseUrl(url)
                .client(okHttpClient)
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .build();
        return retrofit.create(tClass);
    }

    public static ServiceApi getServiceApi() {
        if (serviceApi == null) {
            synchronized (ServiceApi.class){
                if (serviceApi == null) {
                    serviceApi=createAPI(ServiceApi.class,API.HOST);
                }
            }
        }
        return serviceApi;
    }
}
OnNetListener
public interface OnNetListener<T> {
    public void onSuccess(T t);

    public void onFailure(Exception e);
}