Retrofit有参无参接口拼接GET

封装接口公共部分

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 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 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 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 = appService.getApp2(i);
        app2.enqueue(new Callback() {
            @Override
            public void onResponse(Call call, Response response) {
                App2 body = response.body();
            }

            @Override
            public void onFailure(Call call, Throwable t) {

            }
        });
        //无参数的
        /*
        Call app1 = app.getApp1();
        app1.enqueue(new Callback() {
            @Override
            public void onResponse(Call call, Response response) {
                App1 body = response.body();

            }

            @Override
            public void onFailure(Call call, Throwable t) {

            }
        });*/
    }
}

你可能感兴趣的:(Retrofit有参无参接口拼接GET)