由于项目的需要,上传与返回的数据都要加密,并用到的返回的报文头字段进行解密。若用Retrofit2.0 应该怎样处理呢,下面我给大家解读一下。
在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中的一个参数
除了报文与接口地址不同外,其他的包括头信息、解析的报文格式为String字符串、请求超时间等,这里我们可以统一配置。详见代码吧
Retrofit给我们提供的转化库为GsonConverterFactory,在这里,由于返回的是String,我们需要自定义转化库。
1、StringConverterFactory,继承Converter.Factory
2、重写responseBodyConverter方法,自定义StringResponseBodyConverter 类,实现Converter接口。
3、重写requestBodyConverter方法,自定义StringRequestBodyConverter类,实现Converter接口
4、StringRequestBodyConverter类中,重写convert方法,上传的报文信息要在这里加密处理。
自定义API接口
@POST
Observable> getResponse(@Url String string1, @Body String string);
由于项目的接口地址类似这样的,是上传param是参数形式的接口,这里我们把URL地址放在@URL里。并把请求的字符串放在@Body里。
为了简单实现该功能,并能清楚的告诉大家,我们直接在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() {
// @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() {
// @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() {
// @Override
// public void onResponse(Call call, Response 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 call, Throwable t) {
//
// }
// }) ;
Observable<Response<String>> observable = api.getResponse(interface_url, requestStr);
observable.subscribeOn(Schedulers.io())
.flatMap(new Function, ObservableSource>() {
@Override
public ObservableSource apply(Response 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() {
@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() {
@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();
}
}
这位老师一共写了三篇,大家可以学习一下。
手把手教你使用 RxJava 2.0
https://www.jianshu.com/p/d149043d103a