Retrofit2.0 处理返回的加密String字符串
来源:互联网 发布:windows程序开发工具 编辑:程序博客网 时间:2024/05/07 04:27
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.Factory2、重写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
- Retrofit2.0 处理返回的加密String字符串
- retrofit2.0返回string
- Retrofit2.0不进行Json解析,直接查看返回String
- retrofit2.0 解析string
- MD5加密字符串,返回加密后的字符串
- c++的字符串string处理
- c++的字符串string处理
- 对String字符串的处理
- 字符串String的 简单处理
- String处理字符串的技巧
- RxJava Retrofit2 网络请求,返回数据格式统一的数据报文处理方法
- RxJava Retrofit2 网络请求,返回数据格式统一的数据报文处理方法
- JNI String 字符串 的传递与返回
- string 字符串加密
- Retrofit2 结合 Rxjava 解决返回的 JSON
- 对字符串的加密处理_备忘
- retrofit2.0 post提交返回400
- JAVASCRIPT处理返回的XML字符串
- SSH框架搭建
- win10下jdk环境配置好重启以后失效的问题
- Leetcode-Longest Common Prefix
- 获取文件的Hash值代码实现
- XYNUOJ 讨厌的小数点
- Retrofit2.0 处理返回的加密String字符串
- Git上传项目提示Push rejected: Push to origin/master was rejected解决办法
- Excel应用技巧:分列的妙用
- Scala最常用数据结构Map和Tuple解析
- HTML5第一阶段(第四章盒模型和文本溢出)
- 计算机语言简史
- Java基础知识03-数组
- Push failed: Failed with error: fatal: Could not read from remote repository.
- 校赛总结