Retrofit2.0 处理返回的加密String字符串

Retrofit2.0 处理返回的加密String字符串

由于项目的需要,上传与返回的数据都要加密,并用到的返回的报文头字段进行解密。若用Retrofit2.0 应该怎样处理呢,下面我给大家解读一下。

  • 一、配置Retrofit2.0 与 RxJava
  • 二、项目上加解密的处理
  • 三、配置RetrofitUtil工具类
  • 四、自定义String转化库StringConverterFactory
  • 五、编写接口Api
  • 六、使用RxJava2.0获取并解析数据

一、配置Retrofit2.0 与 RxJava

在build.gradle文件下dependencies目录进行配置

//Rxjava
compile ‘io.reactivex.rxjava2:rxjava:2.1.6’
compile ‘io.reactivex.rxjava2:rxandroid:2.0.1’
//Retrofit2.0
compile ‘com.squareup.retrofit2:retrofit:2.3.0’
compile ‘com.squareup.retrofit2:converter-gson:2.3.0’
compile ‘com.squareup.retrofit2:adapter-rxjava2:2.3.0’
compile ‘com.squareup.okhttp3:logging-interceptor:3.8.0’

二、项目上加解密的处理

1、加密

Encryption.dataEncryption(value, RetrofitUtil.uuid);
value为要加密的数据
RetrofitUtil.uuid 为加密的key,在此处加密的key我们使用的是请求报文的头信息,即Headers中的一个参数
2、解密 与加密相似
Encryption.dataDencryption(value, uuid);
value为要解密的数据
uuid 为解密的key,在此处解密的key我们使用的是返回报文的头信息,即Headers中的一个参数

三、配置RetrofitUtil工具类

除了报文与接口地址不同外,其他的包括头信息、解析的报文格式为String字符串、请求超时间等,这里我们可以统一配置。详见代码吧

四、自定义String转化库StringConverterFactory

Retrofit给我们提供的转化库为GsonConverterFactory,在这里,由于返回的是String,我们需要自定义转化库。

1、StringConverterFactory,继承Converter.Factory
2、重写responseBodyConverter方法,自定义StringResponseBodyConverter 类,实现Converter<ResponseBody, String>接口。
3、重写requestBodyConverter方法,自定义StringRequestBodyConverter类,实现Converter<String, RequestBody>接口
4、StringRequestBodyConverter类中,重写convert方法,上传的报文信息要在这里加密处理。

五、编写接口Api

自定义API接口

@POST
    Observable<Response<String>> getResponse(@Url String string1, @Body String string);

由于项目的接口地址类似这样的,是上传param是参数形式的接口,这里我们把URL地址放在@URL里。并把请求的字符串放在@Body里。

六、使用RxJava2.0获取并解析数据

为了简单实现该功能,并能清楚的告诉大家,我们直接在Activity文件下实现网络信息的加载。利用观察者模式实现如下所示

package com.mvp.view;

import android.os.Bundle;
import android.provider.Settings;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.JsonObject;
import com.mvp.app.HttpConstants;
import com.mvp.model.entity.BaseBean;
import com.mvp.model.entity.HttpResult;
import com.mvp.model.http.Api;
import com.mvp.model.http.ApiService;
import com.mvp.model.http.RetrofitUtil;
import com.mvp.model.http.factory.StringConverterFactory;
import com.mvp.util.encry.Encryption;
import com.mvp.util.other.UtilGson;
import com.mvp.util.other.UtilLog;
import com.mvp.util.other.UtilString;

import org.reactivestreams.Subscriber;
import org.reactivestreams.Subscription;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.ObservableSource;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;
import io.reactivex.functions.Predicate;
import io.reactivex.internal.schedulers.NewThreadScheduler;
import io.reactivex.schedulers.Schedulers;
import okhttp3.OkHttpClient;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;
import retrofit2.http.GET;

public class MainActivity extends AppCompatActivity {
    private final String TAG = this.getClass().getSimpleName();
    private String requestStr = "";
    //    private String interface_url = "mobile.do?action=getBranch";
//    private String interface_url = "mobile.do?action=fixCount";
    private String interface_url = "/login.do?action=handleAction";
    @BindView(R.id.test_Post)
    TextView test_Post;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);
        //测试数据  机构查询
//        JsonObject json = new JsonObject();
//        json.addProperty("account_id", "sup");
//        json.addProperty("branch_code", "B");
//        requestStr = json.toString();
        //报修数量数据
//        JsonObject json = new JsonObject();
//        json.addProperty("account_id", "sup");
//        json.addProperty("manufaid", "B");
//        json.addProperty("roleid", "100029");
        JsonObject json = new JsonObject();
        json.addProperty("beanName", "mobileLogin");
        json.addProperty("username", "sn");
        json.addProperty("passwd", "123123");
        requestStr = json.toString();

    }

    @OnClick(R.id.test_Post)
    public void testPost() {
        returnString();

    }

    //post请求返回String类型的加密串
    private void returnString() {
        Retrofit retrofit = create();
        Api api = RetrofitUtil.getApiService();
//        Log.i(TAG,"uuid"+RetrofitUtil.uuid);
//        Observable<String> observable = api.getOrgList(requestStr);
//        observable.subscribeOn(Schedulers.io())
//                .observeOn(AndroidSchedulers.mainThread())
//                .subscribe(new Consumer<String>() {
//                    @Override
//                    public void accept(String str) throws Exception {
//                        System.out.println(str);
//                    }
//                });
        //1 、  Observable  返回response
//        Observable<Response<String>> observable = api.getResponse("mobile.do?action=getBranch",requestStr);
//        observable.subscribeOn(Schedulers.io())
//                .observeOn(AndroidSchedulers.mainThread())
//                .subscribe(new Consumer<Response>() {
//                    @Override
//                    public void accept(Response response) throws Exception {
//                        String uuid = response.headers().get("uuid");
//                        Log.i(TAG, "uuid=" + uuid);
//                        Log.i(TAG, "response=" + response.body());
//                    }
//
//                });

        //2、 用call返回response
//        Call<String> observable = api.getOrg(requestStr);
//        observable.enqueue(new Callback<String>() {
//            @Override
//            public void onResponse(Call<String> call, Response<String> response) {
//                String uuid = response.headers().get("uuid");
//                Log.i(TAG, "uuid=" + uuid);
//                Log.i(TAG, "str=" + call.toString());
//                Log.i(TAG, "response=" + response.body());
//              String data=  Encryption.dataDencryption(response.body(),uuid);
//                Log.i(TAG, "data=" + data);
//            }
//
//            @Override
//            public void onFailure(Call<String> call, Throwable t) {
//
//            }
//        });
        Observable<Response<String>> observable = api.getResponse(interface_url, requestStr);
        observable.subscribeOn(Schedulers.io())
                .flatMap(new Function<Response<String>, ObservableSource<String>>() {
                    @Override
                    public ObservableSource<String> apply(Response<String> response) throws Exception {
                        String uuid = response.headers().get("uuid");
                        String body = response.body();
                        String result=result= Encryption.dataDencryption(body, uuid);
                        return Observable.just(result);
                    }
                })
                .filter(new Predicate<String>() {
                    @Override
                    public boolean test(@NonNull String s) throws Exception {
                        if(UtilString.isNull(s)){
                            System.out.println("未返回数据");
                            return false;
                        }
                        try {
                            BaseBean result = UtilGson.json2bean(s, BaseBean.class);
                            if (result.getResult() == 0) {
                                return true;
                            }
                            return false;
                        } catch (Exception e) {
                            System.out.println("数据解析失败");
                            return false;
                        }
                    }
                })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<String>() {
                    @Override
                    public void accept(String string) throws Exception {
                        System.out.println(string);
                    }
                });
    } ;

    private static Retrofit create() {
        OkHttpClient.Builder builder = new OkHttpClient().newBuilder();
        builder.readTimeout(10, TimeUnit.SECONDS);
        builder.connectTimeout(9, TimeUnit.SECONDS);

        return new Retrofit.Builder().baseUrl(HttpConstants.HOST_SITE_HTTPS)
                .client(builder.build())
                .addConverterFactory(StringConverterFactory.create())
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .build();
    }

}

附:Retrofit2.0的讲解

这位老师一共写了三篇,大家可以学习一下。

手把手教你使用 RxJava 2.0
https://www.jianshu.com/p/d149043d103a

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值