封装Retrofit,RXJAVA,okhttp网络请求的工具

本文介绍了一个使用Retrofit进行网络请求的封装实例,通过单例模式创建Retrofit实例,并利用Gson转换器处理数据。文章详细展示了如何通过该工具类发起GET请求获取新闻数据,并通过回调机制将结果传递给视图层。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

package com.example.weekly_dome.retrofit;

import com.example.weekly_dome.bean.NewsBean;
import com.example.weekly_dome.view.MView;

import java.util.Map;

import okhttp3.OkHttpClient;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * Created by z on 2017/12/30.
 */

public class RetrofitUtils {
    private static volatile RetrofitUtils instance;
    private final Retrofit retrofit;
    private ApiService apiService;

    public RetrofitUtils(String baseUrl){
        retrofit = new Retrofit.Builder()
                .addConverterFactory(GsonConverterFactory.create())
                .client(new OkHttpClient())
                .baseUrl(baseUrl)
                .build();
    }

    public static RetrofitUtils getInstance(String baseUrl){
        if(null==instance){
            synchronized (RetrofitUtils.class){
                if(instance==null){
                    instance=new RetrofitUtils(baseUrl);
                }
            }
        }
        return instance;
    }
public void getNews(final MView mView, Map<String,String> map){
    apiService = retrofit.create(ApiService.class);
    apiService.getData(map).enqueue(new Callback<NewsBean>() {
        @Override
        public void onResponse(Call<NewsBean> call, Response<NewsBean> response) {
            NewsBean body = response.body();
            mView.onSueecss(body);
        }

        @Override
        public void onFailure(Call<NewsBean> call, Throwable t) {
            mView.onFailed(t);
        }
    });
}

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值