retrofit2 基本用法

1.导入相关相关库 

implementation 'com.squareup.retrofit2:retrofit:2.4.0'
implementation 'com.squareup.retrofit2:converter-gson:2.0.2'

 2.书写一个接口

public interface MessageServices {

    @GET("GetMessageData")
    Call<ResponseCls<MessageInfo>> GetMessageData(@Query("userId") String userId, @Query("password") String password);
    
}

3.实体类

public class ResponseCls<T> {

    private boolean status;
    private Integer code;
    private List<String> messages = new ArrayList();

    private T data;

    public ResponseCls() {
    }

    public int  getCode(){

        return this.code;
    }
    
    public T getData() {
        return this.data;
    }
}

3.创建retrofit对象 

       
    Retrofit retrofit =null
 //创建对象
        if ( retrofit == null ){
            retrofit =new Retrofit.Builder().baseUrl( "http://172.17.0.172:49842/api/ZirukPush/" ).addConverterFactory( GsonConverterFactory.create()).build();
        }

 4.调用并返回对象

if ( retrofit!=null){
            //获取MessageServices对象
            final MessageServices messageServices = retrofit.create( MessageServices.class );
            
            Call <ResponseCls<MessageInfo>> call = messageServices.GetMessageData("test","test"  );

            call.enqueue( new Callback<ResponseCls<MessageInfo>>( ) {
                @Override
                public void onResponse(Call <ResponseCls<MessageInfo>> call, Response<ResponseCls<MessageInfo>> response) {
                    if (response != null && response.body() != null && response.body().getData() != null) {
                        // Toast.makeText(getApplicationContext(), response.body().getData().Content, Toast.LENGTH_SHORT).show();
                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                            sendNotification(response.body().getData().Title,response.body().getData().Content);
                        }
                        ZirukPushPlugins.sendEvent( "onReceiveMessageData","模仿页面跳转" );
                    }
                }
                @Override
                public void onFailure(Call<ResponseCls<MessageInfo>> call, Throwable t) {
                    //Toast.makeText(getApplicationContext(), "网络错误", Toast.LENGTH_SHORT).show();
                }
            } ) ;
        }

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值