Retrofit2 使用经验

基本使用方法

1 准备工作

build.gradle:
dependencies {  
    // Retrofit & OkHttp
    compile 'com.squareup.retrofit2:retrofit:2.0.0'
    compile 'com.squareup.retrofit2:converter-gson:2.0.0' 
}
说明:Retrofit2.0默认使用okhttp进行网络处理,不用单独添加。除非你需要特定的版本

2 定义ServiceGenerator:

public class ServiceGenerator {

    public static final String API_BASE_URL = "http://your.api-base.url";

    private static OkHttpClient.Builder httpClient = new OkHttpClient.Builder();

    private static Retrofit.Builder builder =
            new Retrofit.Builder()
                    .baseUrl(API_BASE_URL)
                    .addConverterFactory(GsonConverterFactory.create());

    public static  S createService(Class serviceClass) {
        Retrofit retrofit = builder.client(httpClient.build()).build();
        return retrofit.create(serviceClass);
    }
    }

3 定义请求接口:

GET:
public interface GitHubClient {  
    @GET("/repos/{owner}/{repo}/contributors")
    Call> contributors(
        @Path("owner") String owner,
        @Path("repo") String repo
    );
}

public class Contributor {  
    String login;
    int contributions;
}

4 发起网络请求

public static void main(String... args) {  
    // Create a very simple REST adapter which points the GitHub API endpoint.
    GitHubClient client = ServiceGenerator.createService(GitHubClient.class);

    // Fetch and print a list of the contributors to this library.
    Call> call =
        client.contributors("fs_opensource", "android-boilerplate");

    try {
        List contributors = call.execute().body();
    } catch (IOException e) {
        // handle errors
    }

    for (Contributor contributor : contributors) {
        System.out.println(
                contributor.login + " (" + contributor.contributions + ")");
    }
}

进阶《一》

GET方法:

@Path:路径参数
@Query:?后面的参数,例如:?expand="dddddd"
@GET("users/{user_id}/activities/{name}/reward")
    Call putReward(
            @Path("user_id") String user_id,
            @Path("name") String name,
            @Query("expand") String expand

    );

POST方法:


 @FormUrlEncoded
 @POST("users/{user_id}/activities/{huodong_id}/bj")
 Call<ResponseBody> huodongSample(
            @Path("user_id") String user_id,
            @Path("huodong_id") String activity_id,
            @Field("code") String code
 );

 @Field:Post传递的参数
 @FormUrlEncoded:如果POST请求,传递数据,必须要有

统一处理的一些逻辑:

没有网络的处理:

Retrofit2.0无网状态处理:
    无网会回调onFailure(Call call, Throwable t)方法,在该方法内部调用showFailure即可
public void showFailure( Throwable t) {
        if(t.getMessage() != null && t.getMessage().startsWith("Failed to connect to")){
            Log.d("lincoln","当前网络情况不稳定");
        }
    }

每次请求都添加Header或者Token:

    添加intercept即可

httpClient.addInterceptor(new Interceptor() {  
    @Override
    public Response intercept(Interceptor.Chain chain) throws IOException {
        Request original = chain.request();

        Request request = original.newBuilder()
            .header("User-Agent", "Your-App-Name")
            .header("Accept", "application/vnd.yourapi.v1.full+json")
            .method(original.method(), original.body())
            .build();

        return chain.proceed(request);
    }
}

Retrofit2 使用经验_第1张图片

你可能感兴趣的:(Android框架开发)