封装接口公共部分
public class Api {
public static String api1="http://service.meiyinkeqiu.com/";
public static String api2="http://gank.io/api/";
public static String api3="http://www.93.gov.cn/93app/";
}
GET有参无参拼接 接口 App1 App2 App3分别代表三个bean类
public interface AppService {
/*
*
* 无参get请求
* http://service.meiyinkeqiu.com/service/ads/cptj
*
* */
@GET("service/ads/cptj")
Call<App1> getApp1();
/**
* 有参get请求
* http://gank.io/api/data/%E7%A6%8F%E5%88%A9/10/1
*
*/
@GET("data/%E7%A6%8F%E5%88%A9/10/{page}")
Call<App2> getApp2(@Path("page") int page);
/**
* http://www.93.gov.cn/93app/data.do?channelId=0&startNum=0
* http://www.93.gov.cn/93app/data.do
* channelId
* startNum
* 拼接 ? &
* 为主
*/
@GET("data.do")
Call<App3> getApp3(@Query("channelId") int channelId,@Query("startNum") int startNum);
}
有参调用和无参调用
public class MainActivity extends AppCompatActivity {
int i=1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getP();
}
public void getP() {
HttpLoggingInterceptor httpLoggingInterceptor=new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() {
@Override
public void log(String message) {
// Log.d("xxx",message);
}
});
httpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
OkHttpClient okHttpClient=new OkHttpClient.Builder().addInterceptor(httpLoggingInterceptor).build();
Retrofit retrofit=new Retrofit.Builder().client(okHttpClient).addConverterFactory(GsonConverterFactory.create())
//用哪个接口直接调用Api里封装的
.baseUrl(Api.api2).build();
AppService appService = retrofit.create(AppService.class);
//有参数的
Call<App2> app2 = appService.getApp2(i);
app2.enqueue(new Callback<App2>() {
@Override
public void onResponse(Call<App2> call, Response<App2> response) {
App2 body = response.body();
}
@Override
public void onFailure(Call<App2> call, Throwable t) {
}
});
//无参数的
/*
Call<App1> app1 = app.getApp1();
app1.enqueue(new Callback<App1>() {
@Override
public void onResponse(Call<App1> call, Response<App1> response) {
App1 body = response.body();
}
@Override
public void onFailure(Call<App1> call, Throwable t) {
}
});*/
}
}