Android-网络哀求库Retrofit的使用

开发者 2024-9-12 21:37:22 92 0 来自 中国
在一样平常的Android项目开辟大概维护,我们都会使用大概遇到Retrofit网络哀求库。这篇博客分享我相识的Retrofit干系的知识,渴望对开文章的小搭档有所资助。
Retrofit

实用Android网络哀求库。
Retrofit导入项目

implementation('com.squareup.retrofit2:retrofit:2.9.0')停止我发布博客,开源库版本是2.9.0。最新的版本请检察开源库的wiki
一样平常情况下我都会参加分析干系的开源库,我个人比力喜好Gson分析库:
implementation 'com.squareup.retrofit2:converter-gson:2.4.0'Retrofit简朴使用

我举得例子都是来源开源库的文档。
1、创建当地的接口文件:
public interface GitHubService {  @GET("users/{user}/repos")  Call<List<Repo>> listRepos(@Path("user") String user);}2、创建Retrofit哀求底子设置:
Retrofit retrofit = new Retrofit.Builder()    .baseUrl("https://api.github.com/")    .build();GitHubService service = retrofit.create(GitHubService.class);3、每个Call创建的GitHubService都可以向服务器发出同步或异步 HTTP 哀求:
Call<List<Repo>> repos = service.listRepos("octocat");Get哀求的注解

@GET("users/list")在链接中指定参数:
@GET("users/list?sort=desc")动态更换链接的参数,好比是id:
@GET("group/{id}/users")Call<List<User>> groupList(@Path("id") int groupId);Post哀求的注解

@POST("users/new")Call<User> createUser(@Body User user);
您需要登录后才可以回帖 登录 | 立即注册

Powered by CangBaoKu v1.0 小黑屋藏宝库It社区( 冀ICP备14008649号 )

GMT+8, 2025-4-10 10:47, Processed in 0.167959 second(s), 32 queries.© 2003-2025 cbk Team.

快速回复 返回顶部 返回列表