美文网首页RxJava2
RxJava2+Retrofit2+okhttp3

RxJava2+Retrofit2+okhttp3

作者: 43d60efa37c7 | 来源:发表于2017-08-15 17:48 被阅读369次

    这是最基础的一个网络服务的一个类,初始化OkHttpClient和Retrofit

    public class HttpService {
       
        public static final String BASE_HOST = "http://192.168.0.90:8080/";
    
        private HttpService() {
            throw new AssertionError();
        }
    
        /**
         * 初始化网络通信服务
         */
        public static Retrofit init(final Context context) {
            
            OkHttpClient okHttpClient = new OkHttpClient.Builder().cache(cache)
                    .retryOnConnectionFailure(true)               
                    .connectTimeout(10, TimeUnit.SECONDS)
                    .build();
    
            Retrofit retrofit = new Retrofit.Builder()
                    .client(okHttpClient)                             
                    .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                    .baseUrl(BASE_HOST)
                    .build();
    
            return retrofit;
        }
    }
    
    

    进行网络请求,先构造一个网络请求接口

    public interface TestApi {
        @Headers({"Content-Type: application/json","charset: utf-8"})
        @POST("edu_info/app/BaseApp/updateUser.jspx")
        Observable<ResponseBody> getUserInfo(@Body User user);
    }
    

    进行网络请求

         HttpService.init(context)
                    .create(TestApi.class)
                    .getUserInfo(user)
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new Observer<ResponseBody>() {
                        @Override
                        public void onSubscribe(@NonNull Disposable d) {
    
                        }
    
                        @Override
                        public void onNext(@NonNull ResponseBody responseBody) {
                            //成功
                        }
    
                        @Override
                        public void onError(@NonNull Throwable e) {
                            //错误处理
                        }
    
                        @Override
                        public void onComplete() {
    
                        }
                    });
    

    未完

    相关文章

      网友评论

      本文标题:RxJava2+Retrofit2+okhttp3

      本文链接:https://www.haomeiwen.com/subject/isevrxtx.html