Retrofit(学习自程序员拉大锯)

1.概述

A type-safe HTTP client for Android and Java

Retrofit (square.github.io)

  • Retrofit turns your HTTP API into a Java interface.(将HTTP API转换成为一个java接口)

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

  • The Retrofit class generates an implementation of the GitHubService interface.(Retrofit类生成对应Java接口的实现)

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

  • Each Call from the created GitHubService can make a synchronous or asynchronous HTTP request to the remote webserver.(创建的GitHubService的每个调用都可以向远程Web服务器发出同步或异步的HTTP请求。)

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

  • Use annotations to describe the HTTP request:(利用注解来描述HTTP请求)

    • URL parameter replacement and query parameter support

    • Object conversion to request body (e.g., JSON, protocol buffers)

    • Multipart request body and file upload

2.注解

2.1.1请求方法注解

每个方法都必须有一个HTTP注解,提供请求方法和相对URL。有八个内置注解。HTTP, GET, POST, PUT, PATCH, DELETE, OPTIONS 和 HEAD。资源的相对URL在注释中被指定

@GET("/get/text")
Call<JsonResult> getJson();
​
@POST
Call<PostWithParam> postWithUrl(@Url String url);

2.1.2请求参数注解

  • @Query -url参数

 @GET("/get/param")
 Call<GetWithParamResult> getWithParams(@Query("keyword") String keyword,
                                           @Query("page") String page,
                                           @Query("order") String order);
​

  • @QueryMap -url参数列表

@GET("/get/param")
Call<GetWithParamResult> getWithParams(@QueryMap Map<String,Object> params);

  • @Body -一般用于POST提交数据的body

 @POST("post/comment")
 Call<PostWithParam> postWithBody(@Body CommentItem item);

  • @part--文件上传

 @Multipart
 @POST("file/upload")
 Call<PostFileResult> postFile(@Part MultipartBody.Part part);

3.利用retrofit框架实现网络开发

1.导入依赖

implementation 'com.squareup.retrofit2:retrofit:2.9.0'

2.编写网络请求接口与RetrofitManager类

  • API:

public interface API {
​
    @GET("/get/text")
    Call<JsonResult> getJson();
​
    @GET("/get/param")
    Call<GetWithParamResult> getWithParams(@Query("keyword") String keyword,
                                           @Query("page") String page,
                                           @Query("order") String order);
    @GET("/get/param")
    Call<GetWithParamResult> getWithParams(@QueryMap Map<String,Object> params);
​
    @POST("post/string")
    Call<PostWithParam> postWithParams(@Query("string") String content);
​
    @POST
    Call<PostWithParam> postWithUrl(@Url String url);
​
    @POST("post/comment")
    Call<PostWithParam> postWithBody(@Body CommentItem item);
​
    @Multipart
    @POST("file/upload")
    Call<PostFileResult> postFile(@Part MultipartBody.Part part);
​
    @Multipart
    @POST("files/upload")
    Call<PostFileResult> postFiles(@Part List<MultipartBody.Part> parts);
​
}

  • RetrofitManager

public class RetrofitManager {
​
    private static Retrofit retrofit=new Retrofit.Builder()
            .baseUrl(BASE_URL)
            .addConverterFactory(GsonConverterFactory.create())
            .client(new OkHttpClient.Builder().connectTimeout(1, TimeUnit.MINUTES).build())
            .build();
​
    public static Retrofit getRetrofit(){
        return  retrofit;
    }
}

3.创建对象,调用方法

1)/get/param
​
        Retrofit retrofit = RetrofitManager.getRetrofit();
        API api = retrofit.create(API.class);//获取网络请求接口的实例
        Call<GetWithParamResult> task = api.getWithParams("你好", "1","0");//对发送的请求进行封装
        task.enqueue(new Callback<GetWithParamResult>() {//发送请求
            @Override
            public void onResponse(Call<GetWithParamResult> call, Response<GetWithParamResult> response) {
                System.out.println(response.code());
                System.out.println(response.body().toString());
            }
            @Override
            public void onFailure(Call<GetWithParamResult> call, Throwable t) {
                System.out.println(t.toString());
            }
        });
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值