• 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();
                        }
                    });

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

  • 相关阅读:
    微信OpenID获取
    2015总结及2016目标
    python start
    csv到mysql数据库如何分割
    读书 --- 老码识途
    读书--编写高质量代码 改善C#程序的157个建议2
    读书--编写高质量代码 改善C#程序的157个建议
    BinarySearch
    在aspx中写c#
    AWS 2020 Innovate所有视频
  • 原文地址:https://www.cnblogs.com/loaderman/p/9778228.html
Copyright © 2020-2023  润新知