- 官网地址:https://square.github.io/retrofit/
- 源码地址:https://github.com/square/retrofit
- 使用示例:<具体有3个步骤--permission--implementation--example>
(1)添加权限
<uses-permission android:name="android.permission.INTERNET"/>
(2)加入引用
implementation 'com.google.code.gson:gson:2.8.5'
implementation 'com.squareup.retrofit2:retrofit:2.4.0'
implementation 'com.squareup.retrofit2:converter-gson:2.4.0'
(3)java代码
public class RetrofitUtil {
private static Retrofit mRetrofit;
private static GithubApiService mGithubApiService;
private RetrofitUtil() {
}
private static Retrofit getRetrofit() {
if (mRetrofit == null) {
mRetrofit = new Retrofit.Builder()
.baseUrl("https://api.github.com/")
.addConverterFactory(GsonConverterFactory.create())
.build();
}
return mRetrofit;
}
public static GithubApiService getGithubApiService() {
if (mGithubApiService == null) {
mGithubApiService = getRetrofit().create(GithubApiService.class);
}
return mGithubApiService;
}
}
public interface GithubApiService {
@GET("users/{user}/repos")
Call<ResponseBody> getResponseBody(@Path("user") String user);
@GET("users/{user}/repos")
Call<List<Repo>> listRepos(@Path("user") String user);
}
***另外,需要注意以下几点:
<1>如果BaseUrl是以http开头而不是https,需要在manifest.xml的application节点下添加:
android:usesCleartextTraffic="true"