我的 buid.gradle 就是这样。
implementation 'com.squareup.retrofit2:retrofit:2.3.0'
implementation 'com.squareup.retrofit2:converter-gson:2.3.0'
implementation 'com.squareup.okhttp3:logging-interceptor:3.8.0'
implementation 'com.android.support:design:29.0.2'
implementation 'com.github.bumptech.glide:glide:3.7.0'
生成 Api客户端
public class ApiClient {
private static Retrofit retrofit = null;
public static RestApiMethods getRestApiMethods() {
return createRetrofit().create(RestApiMethods.class);
}
private static Retrofit createRetrofit() {
if (retrofit == null) {
OkHttpClient.Builder httpClient = getBuilder();
httpClient.protocols(Arrays.asList(Protocol.HTTP_1_1));
retrofit = new Retrofit.Builder()
.baseUrl(BuildConfig.BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.client(httpClient.build())
.build();
}
return retrofit;
}
@NonNull
private static OkHttpClient.Builder getBuilder() {
HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
// set your desired log level
if (BuildConfig.IS_DEBUG)
logging.setLevel(HttpLoggingInterceptor.Level.BODY);
OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
httpClient.connectTimeout((long)60 * 3, TimeUnit.SECONDS)
.readTimeout((long)60 * 3, TimeUnit.SECONDS)
.writeTimeout((long)60 * 3, TimeUnit.SECONDS);
// add logging as last interceptor
httpClient.addInterceptor(logging);
return httpClient;
}
}
打来的电话
@GET("URL")
Call<ResponseClass> getUser(@Path("id") int id);
调用API时,获得注释错误。 如何使网址类似URL / id?= 1。
答案 0 :(得分:0)
尝试这样
@GET("URL")
Call<ResponseClass> getUser(@Query("id") int id);
答案 1 :(得分:0)
您可以使用@Query
批注向您的API调用添加参数
@GET("URL")
Call<ResponseClass> getUser(@Query("id") int id);
它将生成如下网址:URL?id=your_id
答案 2 :(得分:0)
在您的界面更新getUser()
方法中,并添加@Query
代替@Path
@GET("URL")
Call<ResponseClass> getUser(@Query("id") int id);
如果是POST
请求,并且您想发送FormUrlEncoded
值,请使用此代码
@FormUrlEncoded
@POST("URL")
Call<ResponseClass> getUser(@Field("id") int id);