安卓使用网络请求框架Retrofit和OKGO的封装_@formurlencoded @post("/pdaservice/login") public -程序员宅基地

技术标签: 安卓  

implementation ‘com.lzy.net:okgo:2.1.4’//OKGO库
比较简单的调用如下:
public static void doRequestGetGiftCabinetList(String id, StringCallback callback) {

    OkGo.get(AppConfig.API_DOMAIN + "/user_api/request_get_gift_cabinet")
            .params("to_user_id", id)
            .tag("doRequestGetGiftCabinetList")
            .cacheMode(CacheMode.DEFAULT)
            .execute(callback);
}

以下是Retrofit的的用法,搭配rxjava使用:
@POST(“api/sso/login”)
@FormUrlEncoded
Observable phoneregister(@Field(“appid”) String appid);

以下是直接使用:
@GET("/reverse_geocoding/v3")
Call findLocation(@Query(“location”) String location, @Query(“ak”) String ak);

以下是RetrofitClient封装单例类, 实现网络请求,可以复制直接使用,在下面有配合rxjava使用的示例代码:

import android.content.Context;
import android.text.TextUtils;

import com.sim.chongwukongjing.BuildConfig;

import java.io.File;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
import me.goldze.mvvmhabit.http.cookie.CookieJarImpl;
import me.goldze.mvvmhabit.http.cookie.store.PersistentCookieStore;
import me.goldze.mvvmhabit.http.interceptor.BaseInterceptor;
import me.goldze.mvvmhabit.http.interceptor.CacheInterceptor;
import me.goldze.mvvmhabit.http.interceptor.logging.Level;
import me.goldze.mvvmhabit.http.interceptor.logging.LoggingInterceptor;
import me.goldze.mvvmhabit.utils.KLog;
import me.goldze.mvvmhabit.utils.Utils;
import okhttp3.Cache;
import okhttp3.ConnectionPool;
import okhttp3.OkHttpClient;
import okhttp3.internal.platform.Platform;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 *
 * @author goldze
 * @date 2017/5/10
 * RetrofitClient封装单例类, 实现网络请求
 */
public class RetrofitClient {
    //超时时间
    private static final int DEFAULT_TIMEOUT = 20;
    //缓存时间
    private static final int CACHE_TIMEOUT = 10 * 1024 * 1024;
    //服务端根路径
    public static String baseUrl = "http://smart.airmedic.cn:9088/arm/";

    private static Context mContext = Utils.getContext();

    private static OkHttpClient okHttpClient;
    private static Retrofit retrofit;

    private Cache cache = null;
    private File httpCacheDirectory;

    private static class SingletonHolder {
        private static RetrofitClient INSTANCE = new RetrofitClient();
    }

    public static RetrofitClient getInstance() {
        return SingletonHolder.INSTANCE;
    }

    private RetrofitClient() {
        this(baseUrl, null);
    }

    private RetrofitClient(String url, Map<String, String> headers) {

        if (TextUtils.isEmpty(url)) {
            url = baseUrl;
        }

        if (httpCacheDirectory == null) {
            httpCacheDirectory = new File(mContext.getCacheDir(), "goldze_cache");
        }

        try {
            if (cache == null) {
                cache = new Cache(httpCacheDirectory, CACHE_TIMEOUT);
            }
        } catch (Exception e) {
            KLog.e("Could not create http cache", e);
        }
        HttpsUtils.SSLParams sslParams = HttpsUtils.getSslSocketFactory();
        okHttpClient = new OkHttpClient.Builder()
                .cookieJar(new CookieJarImpl(new PersistentCookieStore(mContext)))
//                .cache(cache)
                .addInterceptor(new BaseInterceptor(headers))
                .addInterceptor(new CacheInterceptor(mContext))
                .sslSocketFactory(sslParams.sSLSocketFactory, sslParams.trustManager)
                .addInterceptor(new LoggingInterceptor
                        .Builder()//构建者模式
                        .loggable(BuildConfig.DEBUG) //是否开启日志打印
                        .setLevel(Level.BASIC) //打印的等级
                        .log(Platform.INFO) // 打印类型
                        .request("Request") // request的Tag
                        .response("Response")// Response的Tag
                        .addHeader("log-header", "I am the log request header.") // 添加打印头, 注意 key 和 value 都不能是中文
                        .build()
                )
                .connectTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS)
                .writeTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS)
                .connectionPool(new ConnectionPool(8, 15, TimeUnit.SECONDS))
                // 这里你可以根据自己的机型设置同时连接的个数和时间,我这里8个,和每个保持时间为10s
                .build();
        retrofit = new Retrofit.Builder()
                .client(okHttpClient)
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .baseUrl(url)
                .build();

    }

    /**
     * create you ApiService
     * Create an implementation of the API endpoints defined by the {@code service} interface.
     */
    public static <T> T create(final Class<T> service) {
        if (service == null) {
            throw new RuntimeException("Api service is null!");
        }
        if(retrofit == null){
            synchronized (RetrofitClient.class){
                if(retrofit == null){
                    new RetrofitClient();
                }
            }
        }
        return retrofit.create(service);
    }

    /**
     * /**
     * execute your customer API
     * For example:
     * MyApiService service =
     * RetrofitClient.getInstance(MainActivity.this).create(MyApiService.class);
     * <p>
     * RetrofitClient.getInstance(MainActivity.this)
     * .execute(service.lgon("name", "password"), subscriber)
     * * @param subscriber
     */

    public static <T> T execute(Observable<T> observable, Observer<T> subscriber) {
        observable.subscribeOn(Schedulers.io())
                .unsubscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(subscriber);

        return null;
    }
}

以下是可以在present层使用的Retrofit和rxjava的示例代码:

private void login() {
        HttpApi mloginApi;
        mloginApi = RetrofitClient.create(HttpApi.class);//对上面封装的使用
        String motime = String.valueOf(System.currentTimeMillis());

        HashMap<String, String> hashMap = new HashMap<>();
        hashMap.put("motime",motime);
        hashMap.put("smstype","REG");
        hashMap.put("phone",phone.getText().toString());

        String androidID = Settings.System.getString(this.getContentResolver(), Settings.System.ANDROID_ID);
        //关于安卓设备唯一序列号的使用可以看我之前的博文
        String sign = signMD5("",hashMap);//加密签名

        FormBody body = new FormBody.Builder()
                    .add("appid", "")
                    .add("motime",  motime)
                    .add("sign", "")
                    .add("phone", phone.getText().toString())
                    .add("mac", androidID)
                    .add("passwd",editText3.getText().toString())
                    .build();

        Observable<LoginResult> observable = mloginApi.login(body);
        observable.subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<LoginResult>() {
                    @Override
                    public void accept(LoginResult baseInfo) throws Exception {
                        if ("10000".equals(baseInfo.getCode())){
                            ToastUtils.showShort(baseInfo.getMsg());
                            if (checkBox2.isChecked()){
                                SharedPreferencesUtil.saveLoginInfo(getApplicationContext(),phone.getText().toString(),editText3.getText().toString());
                            }else {
                                SharedPreferencesUtil.deleteUser(getApplicationContext());
                            }
                            MyApplication.getInstance().setLoginResult(baseInfo);
                            if (baseInfo.getData().getDcvcnt()==0){
                                startActivity(AddMachineActivity.class);
                            }else {
                                startActivity(MyEquipmentAcitivity.class);
                            }

                            finish();
                        }else {
                            ToastUtils.showShort(baseInfo.getMsg());
                        }
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        ToastUtils.showShort("登录失败,请稍后重试");
                    }
                });
    }
版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/weixin_42446445/article/details/99940660

智能推荐

MATLAB的GUI 程序设计_制作一个曲面光照效果的演示界面,如图所示,三个弹出式菜单分别用于选择曲面形式、-程序员宅基地

文章浏览阅读7.2k次,点赞7次,收藏60次。第七章 MATLAB的GUI 程序设计Chapter 8: Design of MATLAB of GUI programGUI(Graphical User Interfaces):由各种图形对象组成的用户界面,在这种用户界面下,用户的命令和对程序的控制是通过“选择”各种图形对象来实现的。目前90%以上的应用程序和软件都是在GUI下运行的。MATLAB有两种GUI用户界面控件的创建方式,基于命令行的方式用程序来制作和基于GUI的方式制作。这里主要介绍基于GUI的方式。MATLAB 的._制作一个曲面光照效果的演示界面,如图所示,三个弹出式菜单分别用于选择曲面形式、

MT7628开发环境搭建_undefined reference to `llseek-程序员宅基地

文章浏览阅读2.1k次。参考openwrt 快速入门1.环境搭建1.1Ubuntu dockerhttps://www.runoob.com/docker/ubuntu-docker-install.html​1.1.1使用官方安装脚本自动安装安装命令如下:curl -fsSL https://get.docker.com | bash -s docker --mirror Aliyun​ps: 我已经放弃用deepin编译旧版openwrt ,修复了十几个bug还是有bug,无敌下载14.04版本docke_undefined reference to `llseek

13 Kubectl命令概览_kube_ps1关闭-程序员宅基地

文章浏览阅读81次。kubectx:用于切换kubernetes context kube-ps1:为命令行终端增加$PROMPT字段 kube-shell:交互式带命令提示的kubectl终端kube-shell开源项目kube-shell可以为kubectl提供自动的命令提示和补全,使用起来特别方便,推荐给大家。Kube-shell有以下特性:命令提示,给出命令的使用说明 自动补全,列出可选命令并可以通过tab键自动补全,支持模糊搜索 高亮 使用tab键可以列出可选的对象 vim模式M..._kube_ps1关闭

ensp各种报错积累(以及解决方法)_ensp配置路由地址时错误-程序员宅基地

文章浏览阅读1k次,点赞11次,收藏9次。此报错的意思是请续订默认配置,就是让你去一级一级的删除,首先删除你设置的允许vlan通过的命令,然后去取消掉更改的端口类型命令(就是在配置命令前面加一个undo),再去更改端口类型就成功了。此报错的意思是已经加入了接口,不能在修改模式,所以需要先去把端口全部删除,在修改模式即可成功。他的意思就是说这个IP地址已经配置了,不需要在配置了。2.修改链路聚合模式的时候。3.更改IP地址的时候。_ensp配置路由地址时错误

经典JS-序列号_ucfp:74a28a8b-b3fb-4602-ca5f-0ebdf880c1ff-16927960-程序员宅基地

文章浏览阅读10w+次。3D0E1D4E75686FA0FF1C6F6F626F6F6F6F6F6F6F8F381B2FFF2D6FEF396F6F6A1B6E6F6D762B39E3021B282C725C726F4F6F6F6F5F5F5C330E1F06251C335B5E0D580E5E095D575B0E56560B5F0B41051C6F9F4FCC60636EBE7FBE7A3E637EB613394327_ucfp:74a28a8b-b3fb-4602-ca5f-0ebdf880c1ff-1692796091560

Linux下使用crontab定时任务进行Tomcat日志分割_crontab多个任务如何分割-程序员宅基地

文章浏览阅读722次。Linux下使用crontab定时任务进行Tomcat日志分割_crontab多个任务如何分割

随便推点

朴素贝叶斯分类器的例子_朴素贝叶斯分类器 例子-程序员宅基地

文章浏览阅读1.1k次。一、病人分类的例子让我从一个例子开始讲起,你会看到贝叶斯分类器很好懂,一点都不难。某个医院早上收了六个门诊病人,如下表。  症状  职业   疾病  打喷嚏 护士   感冒   打喷嚏 农夫   过敏   头痛  建筑工人 脑震荡   头痛  建筑工人 感冒   打喷嚏 教师   感冒   头痛  教师   脑震荡现在又来了第七个病人,是一个打喷嚏的建筑工人。请问他患上感冒的概率有多大?根据贝叶斯..._朴素贝叶斯分类器 例子

当mysql数据库转换为sqlserver数据库时常见报错_mysql 数据导出在sqlserver不能用-程序员宅基地

文章浏览阅读527次。↵下面是我在把mysql数据库转换为sqlserver数据库时候遇到过的一些错,踩过的坑,把它总结下来防止以后再出错。报错 1:com.microsoft.sqlserver.jdbc.SQLServerException: 仅当使用了列列表并且 IDENTITY_INSERT 为 ON 时,才能为表'user_student'中的标识列指定显式值。出错原因:当mysql数据库转换为sqlserver数据库时,如果第一个id设置为自动递增,那么String sql = "..._mysql 数据导出在sqlserver不能用

LeetCode 刷题常用数据结构(Java 中的实现)_javalist集合map组合刷题 leetcode-程序员宅基地

文章浏览阅读1.9k次,点赞4次,收藏27次。记录常用数据结构(栈、队列、数组、列表、字符串、集合等),在 Java 中如何使用它的实现类。_javalist集合map组合刷题 leetcode

Visual Studio Code 设置成中文_visualstudiocode中文-程序员宅基地

文章浏览阅读6.7k次,点赞5次,收藏4次。Visual Studio Code 编辑器设置成中文 分2个步骤1、【查看】--【扩展】(Ctrl+Shift+X) 在扩展:商店中输入Chinese,搜索到 适用于 VS Code 的中文(简体)语言包,点击安装; 2、Ctrl+Shift+P,调出搜索框,输入 Configure Display Language,选中此配置项; 把配置页面中的"..._visualstudiocode中文

[TypeScript][JavaScript]数组遍历方法总结_typescript 数组遍历-程序员宅基地

文章浏览阅读1.2k次。本文整理自:https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Array对比every(),some(),includes(),indexOf(),lastIndexOf(),find(),findIndex(),forEach(),map(),filter(),fill()..._typescript 数组遍历

MySQL数据库的基本概念与安装-程序员宅基地

文章浏览阅读1.2k次,点赞26次,收藏23次。数据库作为一种系统化的数据存储、管理和检索的软件,已成为我们日常生活和工作中不可或缺的一部分,无论是电子商务网站、社交媒体平台,还是企业内部的各种信息系统,背后都有数据库的身影

推荐文章

热门文章

相关标签