Retrofit2+OkHttp3+RxJava网络请求封装

2023-12-09 16:58

本文主要是介绍Retrofit2+OkHttp3+RxJava网络请求封装,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

 

第一步:  添加依赖

//RxJava
implementation 'io.reactivex:rxjava:1.1.3'
//RxAndroid
implementation 'io.reactivex:rxandroid:1.1.0'
//retrofit
implementation 'com.squareup.retrofit2:retrofit:2.0.0'
//retrofit依赖Gson
implementation 'com.squareup.retrofit2:converter-gson:2.0.0'
//OkHttp
implementation 'com.squareup.okhttp3:okhttp:3.8.0'
//retrofit依赖RxJava
implementation 'com.squareup.retrofit2:adapter-rxjava:2.0.0'
//okhttp
implementation 'com.squareup.okhttp3:logging-interceptor:3.6.0'
//日志
implementation 'com.orhanobut:logger:2.2.0'

 

第二步:

RetrofitServiceManager
package com.example.myapplication;import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.orhanobut.logger.Logger;import java.io.IOException;
import java.util.concurrent.TimeUnit;import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;/*** Created by ShinnyYang on 2020/8/3.*/
public class RetrofitServiceManager {private static final int DEFAULT_CONNECT_TIME = 12;private static final int DEFAULT_WRITE_TIME = 12;private static final int DEFAULT_READ_TIME = 12;private static OkHttpClient okHttpClient;private static final String REQUEST_PATH = "http://admin.qianduoduo.cy6.co";private static Retrofit retrofit;private RetrofitServiceManager() {retrofit = new Retrofit.Builder().client(initOKHttp())//设置使用okhttp网络请求.baseUrl(REQUEST_PATH)//设置服务器路径.addConverterFactory(GsonConverterFactory.create())//添加转化库,默认是Gson.addCallAdapterFactory(RxJavaCallAdapterFactory.create())//添加回调库,采用RxJava.build();}public static OkHttpClient initOKHttp() {if (okHttpClient == null) {HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() {@Overridepublic void log(String message) {//防止&、=都被转义Logger.e("okhttp==" + message);}});loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);okHttpClient = new OkHttpClient.Builder()/*  .addInterceptor(new Interceptor() {@Overridepublic Response intercept(Chain chain) throws IOException {Request request = chain.request().newBuilder().addHeader("AuthToken", "").build();return chain.proceed(request);}})*/.connectTimeout(12, TimeUnit.SECONDS).readTimeout(12, TimeUnit.SECONDS).writeTimeout(12, TimeUnit.SECONDS).addInterceptor(loggingInterceptor).build();}return okHttpClient;}private static class SingletonHolder {private static final RetrofitServiceManager INSTANCE = new RetrofitServiceManager();}/** 获取RetrofitServiceManager**/public static RetrofitServiceManager getInstance() {return SingletonHolder.INSTANCE;}public <T> T create(Class<T> service) {return retrofit.create(service);}
}

 

 

第三步:

AllApi

 

package com.example.myapplication;import com.example.myapplication.bean.HomeListBean;import java.util.Map;import retrofit2.http.GET;
import retrofit2.http.Query;
import retrofit2.http.QueryMap;
import rx.Observable;/*** Created by ShinnyYang on 2020/8/3.*/
public interface AllApi {@GET("/qddapiv2/index/list.php")Observable<HomeListBean> getHomeList(@QueryMap Map<String, Object> map);
}

 

第四步:

HttpModel

 

package com.example.myapplication;import com.example.myapplication.bean.HomeListBean;import java.util.Map;import rx.Observable;
import rx.Observer;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;/*** Created by ShinnyYang on 2020/8/3.*/
public class HttpModel {private static AllApi movieService = RetrofitServiceManager.getInstance().create(AllApi.class);public static void getList(Map<String, Object> map,Observer<HomeListBean> observer) {setSubscribe(movieService.getHomeList(map), observer);}private static <T> void setSubscribe(Observable<T> observable, Observer<T> observer) {observable.subscribeOn(Schedulers.io()).subscribeOn(Schedulers.newThread())//子线程访问网络.observeOn(AndroidSchedulers.mainThread())//回调到主线程.subscribe(observer);}
}

 

第五步 :

private void getData() {Map<String, Object> map = new HashMap<>();map.put("page", "1");map.put("auth", "");map.put("time", "1596091163");map.put("token", "ZcfveU5pHeYiqH6lfvE9qeIquMPVGnSloW7TYnryFCI=");map.put("uid", "0730096");map.put("action", "margin");map.put("device_no", "ece430f2-cda1-4c5c-be1e-a0657395470e");HttpModel.getList(map, new Observer<HomeListBean>() {@Overridepublic void onCompleted() {Toast.makeText(getApplicationContext(), "onCompleted", Toast.LENGTH_SHORT).show();}@Overridepublic void onError(Throwable e) {Logger.e("onError==>" + e.getMessage());}@Overridepublic void onNext(HomeListBean homeListBean) {Logger.e("onSuccess==>" + homeListBean.toString());}});
}

 

实体bean

 

package com.example.myapplication.bean;import java.util.List;public class HomeListBean {/*** status : 1* time : 1595819291* pagenum : 1* data : [{"task_id":"254","type_id":"11","thumb":"http://admin.qianduoduo.cy6.co/api/img/5.png","title":"999999999999999","unit_price":"400.00","num":"12","is_jingpin":"0","margin_per":1,"finish":2,"type_name":"微信转发","extra":"75"}]* msg : 查询成功*/private int status;private int time;private int pagenum;private String msg;private List<DataBean> data;public int getStatus() {return status;}public void setStatus(int status) {this.status = status;}public int getTime() {return time;}public void setTime(int time) {this.time = time;}public int getPagenum() {return pagenum;}public void setPagenum(int pagenum) {this.pagenum = pagenum;}public String getMsg() {return msg;}public void setMsg(String msg) {this.msg = msg;}public List<DataBean> getData() {return data;}public void setData(List<DataBean> data) {this.data = data;}@Overridepublic String toString() {return "HomeListBean{" +"status=" + status +", time=" + time +", pagenum=" + pagenum +", msg='" + msg + '\'' +", data=" + data +'}';}public static class DataBean {/*** task_id : 254* type_id : 11* thumb : http://admin.qianduoduo.cy6.co/api/img/5.png* title : 999999999999999* unit_price : 400.00* num : 12* is_jingpin : 0* margin_per : 1* finish : 2* type_name : 微信转发* extra : 75*/private String task_id;private String type_id;private String thumb;private String title;private String unit_price;private String num;private String is_jingpin;private int margin_per;private int finish;private String type_name;private String extra;@Overridepublic String toString() {return "DataBean{" +"task_id='" + task_id + '\'' +", type_id='" + type_id + '\'' +", thumb='" + thumb + '\'' +", title='" + title + '\'' +", unit_price='" + unit_price + '\'' +", num='" + num + '\'' +", is_jingpin='" + is_jingpin + '\'' +", margin_per=" + margin_per +", finish=" + finish +", type_name='" + type_name + '\'' +", extra='" + extra + '\'' +'}';}public String getTask_id() {return task_id;}public void setTask_id(String task_id) {this.task_id = task_id;}public String getType_id() {return type_id;}public void setType_id(String type_id) {this.type_id = type_id;}public String getThumb() {return thumb;}public void setThumb(String thumb) {this.thumb = thumb;}public String getTitle() {return title;}public void setTitle(String title) {this.title = title;}public String getUnit_price() {return unit_price;}public void setUnit_price(String unit_price) {this.unit_price = unit_price;}public String getNum() {return num;}public void setNum(String num) {this.num = num;}public String getIs_jingpin() {return is_jingpin;}public void setIs_jingpin(String is_jingpin) {this.is_jingpin = is_jingpin;}public int getMargin_per() {return margin_per;}public void setMargin_per(int margin_per) {this.margin_per = margin_per;}public int getFinish() {return finish;}public void setFinish(int finish) {this.finish = finish;}public String getType_name() {return type_name;}public void setType_name(String type_name) {this.type_name = type_name;}public String getExtra() {return extra;}public void setExtra(String extra) {this.extra = extra;}}
}

 

 

  完成!!!!!

常用的注解:

@GET GET请求方式

@POST POST请求方式

@Query GET请求参数

@Header用来添加Header请求头

@FormUrlEncoded post请求头标示 其他注解请求方式:

@PUT 表示这是一个PUT请求

@DELETE 表示这是一个DELETE请求

@HEAD 表示这是一个HEAD请求

@OPTIONS 表示这是一个OPTION请求

@PATCH 表示这是一个PAT请求

这篇关于Retrofit2+OkHttp3+RxJava网络请求封装的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/474451

相关文章

Java编译生成多个.class文件的原理和作用

《Java编译生成多个.class文件的原理和作用》作为一名经验丰富的开发者,在Java项目中执行编译后,可能会发现一个.java源文件有时会产生多个.class文件,从技术实现层面详细剖析这一现象... 目录一、内部类机制与.class文件生成成员内部类(常规内部类)局部内部类(方法内部类)匿名内部类二、

SpringBoot实现数据库读写分离的3种方法小结

《SpringBoot实现数据库读写分离的3种方法小结》为了提高系统的读写性能和可用性,读写分离是一种经典的数据库架构模式,在SpringBoot应用中,有多种方式可以实现数据库读写分离,本文将介绍三... 目录一、数据库读写分离概述二、方案一:基于AbstractRoutingDataSource实现动态

Linux系统配置NAT网络模式的详细步骤(附图文)

《Linux系统配置NAT网络模式的详细步骤(附图文)》本文详细指导如何在VMware环境下配置NAT网络模式,包括设置主机和虚拟机的IP地址、网关,以及针对Linux和Windows系统的具体步骤,... 目录一、配置NAT网络模式二、设置虚拟机交换机网关2.1 打开虚拟机2.2 管理员授权2.3 设置子

揭秘Python Socket网络编程的7种硬核用法

《揭秘PythonSocket网络编程的7种硬核用法》Socket不仅能做聊天室,还能干一大堆硬核操作,这篇文章就带大家看看Python网络编程的7种超实用玩法,感兴趣的小伙伴可以跟随小编一起... 目录1.端口扫描器:探测开放端口2.简易 HTTP 服务器:10 秒搭个网页3.局域网游戏:多人联机对战4.

Springboot @Autowired和@Resource的区别解析

《Springboot@Autowired和@Resource的区别解析》@Resource是JDK提供的注解,只是Spring在实现上提供了这个注解的功能支持,本文给大家介绍Springboot@... 目录【一】定义【1】@Autowired【2】@Resource【二】区别【1】包含的属性不同【2】@

springboot循环依赖问题案例代码及解决办法

《springboot循环依赖问题案例代码及解决办法》在SpringBoot中,如果两个或多个Bean之间存在循环依赖(即BeanA依赖BeanB,而BeanB又依赖BeanA),会导致Spring的... 目录1. 什么是循环依赖?2. 循环依赖的场景案例3. 解决循环依赖的常见方法方法 1:使用 @La

Java枚举类实现Key-Value映射的多种实现方式

《Java枚举类实现Key-Value映射的多种实现方式》在Java开发中,枚举(Enum)是一种特殊的类,本文将详细介绍Java枚举类实现key-value映射的多种方式,有需要的小伙伴可以根据需要... 目录前言一、基础实现方式1.1 为枚举添加属性和构造方法二、http://www.cppcns.co

Elasticsearch 在 Java 中的使用教程

《Elasticsearch在Java中的使用教程》Elasticsearch是一个分布式搜索和分析引擎,基于ApacheLucene构建,能够实现实时数据的存储、搜索、和分析,它广泛应用于全文... 目录1. Elasticsearch 简介2. 环境准备2.1 安装 Elasticsearch2.2 J

Java中的String.valueOf()和toString()方法区别小结

《Java中的String.valueOf()和toString()方法区别小结》字符串操作是开发者日常编程任务中不可或缺的一部分,转换为字符串是一种常见需求,其中最常见的就是String.value... 目录String.valueOf()方法方法定义方法实现使用示例使用场景toString()方法方法

Java中List的contains()方法的使用小结

《Java中List的contains()方法的使用小结》List的contains()方法用于检查列表中是否包含指定的元素,借助equals()方法进行判断,下面就来介绍Java中List的c... 目录详细展开1. 方法签名2. 工作原理3. 使用示例4. 注意事项总结结论:List 的 contain