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<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) {

            }
        });*/
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值