Retrofit的使用

    xiaoxiao2021-03-25  94

    1.把你的HTTP API改造成java接口。

    public interface GitHubService { @GET("users/{user}/repos") Call<List<Repo>> listRepos(@Path("user") String user); }

    2.改造类生成的githubservice接口的实现。

    Retrofit retrofit = new Retrofit.Builder() .baseUrl("https://api.github.com/") .build(); GitHubService service = retrofit.create(GitHubService.class);

    3.列表内容

    Call<List<Repo>> repos = service.listRepos("octocat");

    url参数

    注解方法GET, POST, PUT, DELETE, and HEAD,例如@GET(“users/list?sort=desc”)

    添加日志

    添加依赖 compile ‘com.squareup.okhttp3:logging-interceptor:3.1.2’

    HttpLoggingInterceptor httpLoggingInterceptor = new HttpLoggingInterceptor(); httpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY); OkHttpClient okHttpClient = new OkHttpClient.Builder() .addInterceptor(httpLoggingInterceptor) .build(); Retrofit retrofit = new Retrofit.Builder().addCallAdapterFactory(RxJavaCallAdapterFactory.create()) .client(okHttpClient) .baseUrl("https://api.github.com/") .addConverterFactory(GsonConverterFactory.create()) .build();
    转载请注明原文地址: https://ju.6miu.com/read-18735.html

    最新回复(0)