Retrofit 简单使用

//配置retrofit2.0
implementation 'com.squareup.retrofit2:retrofit:+'
implementation 'com.squareup.retrofit2:converter-gson:+'

1,创建登录接口

public interface ILoginApi {
    //登录接口
    @GET("user/{adc}")
    Call<LoginBean> login(@Path("adc") String path,   @Query("mobile") String mobile, @Query("password") String password);



    @GET("user/login")
    Call<ResponseBody> login1(@Query("mobile") String mobile, @Query("password") String password);


    @GET("user/login")
    Call<LoginBean> login(@QueryMap Map map);


    @FormUrlEncoded
    @POST("user/login")
    Call<LoginBean> loginPost(@Header("source") String source, @Field("mobile") String mobile, @Field("password") String password);

}

2,HttpUtil,饿汉单例模式

public class HttpUtil {

    private static String BASE_URL = "BaseUrl,结尾要以 / 结尾";
    private final Retrofit mRetrofit;

    private static final class SINGLE_INSTANCE {
        private static final HttpUtil INSTANCE = new HttpUtil();
    }

    public static HttpUtil getInstance() {

        return SINGLE_INSTANCE.INSTANCE;
    }


    private HttpUtil() {
        mRetrofit = new Retrofit.Builder()
                .baseUrl(BASE_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .client(getOkHttpClient())
                .build();
    }

    private OkHttpClient getOkHttpClient() {

        return new OkHttpClient.Builder()
                .readTimeout(5, TimeUnit.SECONDS)
                .writeTimeout(5, TimeUnit.SECONDS)
                .connectTimeout(5, TimeUnit.SECONDS)
                .build();
    }

    public <T> T create(Class<T> clazz) {
        return mRetrofit.create(clazz);
    }
}

3,调用

 //利用Retrofit.create方法构造一个Api接口的实例
        ILoginApi iLoginApi = RetrofitManager.getInstance().create(Base网络接口.class);

        //构造一个Call请求,拿到Api接口的实例调用对应的方法去构造一个Call请求
        //比如调用Base接口中的登录方法
        final Call<LoginBean> call = iLoginApi.login("login","15501186523", "123456");

 //一 、 异步请求

        call.enqueue(new Callback<LoginBean>() {
            @Override
            public void onResponse(Call<LoginBean> call, Response<LoginBean> response) {
                if (response.isSuccessful()) {
                    //通过response.body拿到最后解析后的bean对象
                    LoginBean loginBean = response.body();
                    if (loginBean != null & "0".equals(loginBean.getCode())) {
                        Toast.makeText(MainActivity.this, "请求成功", Toast.LENGTH_LONG).show();
                        return;
                    }
                }
                Toast.makeText(MainActivity.this, "请求失败", Toast.LENGTH_LONG).show();
            }

            @Override
            public void onFailure(Call<LoginBean> call, Throwable t) {
                Toast.makeText(MainActivity.this, "请求失败", Toast.LENGTH_LONG).show();

            }
        });

猜你喜欢

转载自blog.csdn.net/liu_qunfeng/article/details/83718853