Android中Retrofit的封装使用

一、大致介绍:

  1. Retrofit:Square 基于OkHttp 实现的一款针对Android 网络请求的框架

  2. OkHttp: Square 开源的网络请求库

  3. RxJava:使得异步操作变得非常简单

二、功能分离

  1. Retrofit 针对请求的数据和请求的结果,使用接口的方式呈现

  2. OkHttp 针对请求的过程

  3. RxJava 针对异步,各种线程之间的切换

三、使用过程

一、添加依赖库

    //RxJava
    compile 'io.reactivex:rxjava:1.1.3'
    //RxAndroid
    compile 'io.reactivex:rxandroid:1.1.0'
    //retrofit
    compile 'com.squareup.retrofit2:retrofit:2.0.0'
    //retrofit依赖Gson
    compile 'com.squareup.retrofit2:converter-gson:2.0.0'
    //OkHttp
    compile 'com.squareup.okhttp3:okhttp:3.2.0'
    //retrofit依赖RxJava
    compile 'com.squareup.retrofit2:adapter-rxjava:2.0.0'

二、创建单例Retrofit接口管理类

import java.util.concurrent.TimeUnit;
import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class RetrofitManager {
	// 请求的URL前缀
    private static final String BASEURL = "http://192.168.42.48:9000/";
    private static Retrofit retrofit;
    private static RetrofitManager retrofitManager;

    //提供共有的方法供外界访问
    public static RetrofitManager newInstance() {
        if (retrofitManager == null) {
            synchronized (RetrofitManager.class) {
                retrofitManager = new RetrofitManager();
            }
        }
        return retrofitManager;
    }

    //通过动态代理生成相应的Http请求
    public <T> T creat(Class<T> t) {
        return retrofit.create(t);
    }

    //构造方法私有化
    private RetrofitManager() {
        retrofit = getRetrofit();
    }

    //构建Ok请求
    private OkHttpClient getOkHttpClient() {
        return new OkHttpClient.Builder()
                .connectTimeout(5000, TimeUnit.MILLISECONDS)
                .build();
    }

    //构建Retrofit
    private Retrofit getRetrofit() {
        return new Retrofit.Builder()
                .baseUrl(BASEURL)
                .client(getOkHttpClient())
                .addConverterFactory(GsonConverterFactory.create())
//                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .build();
    }
}

三、创建接口类

import retrofit2.Call;
import retrofit2.http.Body;
import retrofit2.http.Field;
import retrofit2.http.FormUrlEncoded;
import retrofit2.http.GET;
import retrofit2.http.POST;
import retrofit2.http.Path;
// 对应着服务端的接口
public interface UserService {
	// 如果后端是@RequestParam接受参数,加上@FormUrlEncoded 
    @FormUrlEncoded 
    // 请求路径前不能加 /
    @POST("server/user/login")
    Call<Rs<User>> login(@Field("username") String username, @Field("password") String password);

	//如果后端是@RequestBody接受参数,去除@FormUrlEncoded 
    @POST("server/user/register")
    Call<Rs> register(@Body User user);
    
	// 使用resultful风格请求
    @GET("server/user/getById/{id}")
    Call<Rs<User>> getById(@Path("id") String id);

    @POST("server/user/updateById")
    Call<Rs> updateById(@Body User user);
}

四、调用过程

 // 调用注册接口调试接口
        RetrofitManager.newInstance()
                .creat(UserService.class)
                .login(username,password)
                .enqueue(new Callback<Rs<User>>() {
                    @Override
                    public void onResponse(Call<Rs<User>> call, Response<Rs<User>> response) {
                        LogUtils.i("调用接口成功");
                        if (response.body().getCode() == 20000){
                            Gson gson = new Gson();
                            String json = gson.toJson(response.body().getData());
                            System.out.println(json);
                            SPUtils.getInstance().put("user",json);
                            ToastUtils.showShort("成功!");
                            Intent intent = new Intent(LoginActivity.this, MainActivity.class);
                            startActivity(intent);
                        } else {
                            ToastUtils.showShort("异常!");
                        }
                    }
                    @Override
                    public void onFailure(Call<Rs<User>> call, Throwable t) {
                        LogUtils.e("调用接口异常");
                        ToastUtils.showShort("异常!");
                    }
                });

你可能感兴趣的:(Android,java)