retrofit2+rxjava+okhttp网络请求实现

Posted 码上加油站

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了retrofit2+rxjava+okhttp网络请求实现相关的知识,希望对你有一定的参考价值。

第一步:添加依赖:

    compile ‘io.reactivex:rxandroid:1.2.0‘
    compile ‘com.squareup.retrofit2:adapter-rxjava:2.1.0‘
    compile ‘com.squareup.retrofit2:converter-gson:2.1.0‘
    compile ‘com.squareup.retrofit2:retrofit:2.1.0‘

第二步:创建HttpManager

import android.os.Build;
import okhttp3.Cache;

import com.loaderman.samplecollect.constants.HttpUrlConstants;
import com.loaderman.samplecollect.utils.UiUtil;

import java.io.File;
import java.io.IOException;

import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;
import okhttp3.Response;
/**
 * Created by Administrator on 2018/10/10 0010.
 */

public class HttpManager {
    private static final Interceptor REWRITE_CACHE_CONTROL_INTERCEPTOR = new Interceptor() {
        @Override
        public Response intercept(Chain chain) throws IOException {
            int maxAge = 60 * 5; // 在线缓存在5分钟内可读取
            Request request = chain
                    .request()
                    .newBuilder()
                    .addHeader("User-Agent", Build.BRAND + "/" + Build.MODEL + "/" + Build.VERSION.RELEASE)//添加请求头
                    .header("Cache-Control", "public, max-age=" + maxAge)
                    .build();
            return chain.proceed(request);
        }
    };

    private static File httpCacheDirectory = new File(UiUtil.getContext().getCacheDir(), "mCache");
    private static int          cacheSize          = 10 * 1024 * 1024; // 10 MiB
    private static Cache cache              = new Cache(httpCacheDirectory, cacheSize);
    private static OkHttpClient client             = new OkHttpClient.Builder()
            .addNetworkInterceptor(REWRITE_CACHE_CONTROL_INTERCEPTOR)
            .addInterceptor(REWRITE_CACHE_CONTROL_INTERCEPTOR)
            .cache(cache)
            .build();
    private static HttpManager apiManager;
    public static HttpManager getInstence() {

        if (apiManager == null) {
            synchronized (HttpManager.class) {
                if (apiManager == null) {
                    apiManager = new HttpManager();
                }
            }
        }
        return apiManager;
    }

    private static IHttp httpService;

    public IHttp getHttpService() {
        if (httpService == null) {
            synchronized (new Object()) {
                if (httpService == null) {
                    httpService = new Retrofit
                            .Builder()
                            .baseUrl(HttpUrlConstants.BASE_URL)
                            .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                            .addConverterFactory(GsonConverterFactory.create())
                            .client(client)
                            .build().create(IHttp.class);
                }
            }
        }
        return httpService;
    }
}

第三步;创建IHttp

import com.loaderman.samplecollect.constants.HttpUrlConstants;
import com.loaderman.samplecollect.model.GetDataResult;
import com.loaderman.samplecollect.model.RequestParams;

import java.util.List;
import java.util.Map;

import okhttp3.MultipartBody;
import retrofit2.http.Body;
import retrofit2.http.Field;
import retrofit2.http.FieldMap;
import retrofit2.http.FormUrlEncoded;
import retrofit2.http.GET;
import retrofit2.http.Headers;
import retrofit2.http.Multipart;
import retrofit2.http.POST;
import retrofit2.http.Part;
import retrofit2.http.Query;
import rx.Observable;

/**
 * Created by Administrator on 2018/10/10 0010.
 */

public interface IHttp {

    @GET(HttpUrlConstants.data_url)
    Observable<GetDataResult> getData2(@Query("city") String city);

    @Headers({"Content-Type: application/json;charset=UTF-8"})
    @POST(HttpUrlConstants.data_url)
    Observable<GetDataResult> getData1(@Body RequestParams params);

    @FormUrlEncoded
    @POST(HttpUrlConstants.data_url)
    Observable<GetDataResult> getData3(@Field("city") String city);

    @FormUrlEncoded
    @POST(HttpUrlConstants.data_url)
    Observable<GetDataResult> getData4(@FieldMap Map<String, String> map);
    //上传头像
    @Multipart
    @POST(HttpUrlConstants.data_url)
    Observable<GetDataResult> upLoadIcon(@Part List<MultipartBody.Part> partList);
    
}

第四步 :URL常量管理

public interface HttpUrlConstants {
    String BASE_URL="http://wthrcdn.etouch.cn/";

    String data_url = "weather_mini";
}

第五步 : 代码中进行网络请求 :

示例1:

HttpManager
                .getInstence()
                .getHttpService()
                .getData2("北京市")
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<GetDataResult>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                        LoggerUtil.systemOut(e.toString());
                    }

                    @Override
                    public void onNext(GetDataResult getDataResult) {
                        LoggerUtil.systemOut(getDataResult.toString());
                        ToastUtil.showMsg(MainActivity.this, getDataResult.data.city);
                    }
                });

示例2 :上传头像

  MultipartBody.Builder builder = new MultipartBody.Builder()
                .setType(MultipartBody.FORM)//表单类型
                .addFormDataPart("token", ConfigConstants.getToken(this))
                .addFormDataPart("uid", ConfigConstants.getUid(this))
                .addFormDataPart("sign", ConfigConstants.SIGN)
                ;
        RequestBody imageBody = RequestBody.create(MediaType.parse("image/png"), file);  //multipart/form-data image/png
        builder.addFormDataPart("file", file.getName(), imageBody);//file 后台接收图片流的参数名    +".png"
        List<MultipartBody.Part> parts = builder.build().parts();

        HttpManager
                .getInstence()
                .getLearnCarService()
                .upLoadIcon(parts)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<UpLoadIconEntity>() {
                    @Override
                    public void onCompleted() {
                        
                    }

                    @Override
                    public void onError(Throwable e) {
                       
                    }

                    @Override
                    public void onNext(UpLoadIconEntity upLoadIconEntity) {

                       
                        hideLoading();
                    }
                });

 

到处完成网络请求步骤!!!

以上是关于retrofit2+rxjava+okhttp网络请求实现的主要内容,如果未能解决你的问题,请参考以下文章

网络框架封装(retrofit2+rxjava2+okhttp3)

RxJava2+Retrofit2+RxLifecycle3+OkHttp3网络请求封装(动态演示)

retrofit 2 支持rxjava2了吗

Mvp+Rxjava+Retrofit2.0+Okhttp完善版

使用Retrofit2+RxJava2+ProtoBuf实现网络请求

Android入门第65天-mvvm模式下的retrofit2+okhttp3+rxjava