Retrofit2封装之路(请求参数加密解密)(一)

来源:互联网 发布:芒果tv mac版下载 编辑:程序博客网 时间:2024/06/08 06:23

我还在拥抱Eclipse呐!!!

我使用的版本

retrofit-2.3.0.jar

okio-1.13.0.jar

okhttp-3.8.1.jar

目前项目现阶段使用的网络库是OKhttp3 

现在将Retrofit2 加入到项目中,Retrofit2 OKhttp3 无缝链接么?确实是,代码还是要改动的,权当记录一下改动日志吧!!!

我们的接口不带多级目录,添加参数直接怼的形式

也许你们的接口是这样

https://api.github.com/repos/square/okhttp/issues

也许是这样

https://api.github.com/issues

我们的接口是这样,不带层级,不带层级,不带层级

https://api.github.com


、请求路径构造

http://pan.baidu.com?data=加密json

public interface IBannerService {@FormUrlEncoded@POST("/")public Call<BannerResp> getBanner(@Field("data") String json);}

请求体,响应体构造

public class BannerReq implements Serializable {private static final long serialVersionUID = 1L;public int num;public String version="v1.0.0";public String system = "360";public BannerReq(int num) {super();this.num = num;}@Overridepublic String toString() {return "BannerReq [num=" + num + ", version=" + version + ", system="+ system + "]";}}

public class BannerResp implements Serializable {private static final long serialVersionUID = 1L;public int code;public int num;public String msg;public List<Banner> data;public class Banner implements Serializable {private static final long serialVersionUID = 1L;public String id;public String name;@Overridepublic String toString() {return "Banner [id=" + id + ", name=" + name + "]";}}@Overridepublic String toString() {return "BannerResp [code=" + code + ", num=" + num + ", msg=" + msg+ ", data=" + data + "]";}}
、参数加密解密

public class IGsonFactory extends Converter.Factory {public static IGsonFactory create() {return create(new GsonBuilder().setLenient().create());}public static IGsonFactory create(Gson gson) {if (gson == null)throw new NullPointerException("gson == null");return new IGsonFactory(gson);}private final Gson gson;private IGsonFactory(Gson gson) {this.gson = gson;}@Overridepublic Converter<ResponseBody, ?> responseBodyConverter(Type type,Annotation[] annotations, Retrofit retrofit) {TypeAdapter<?> adapter = gson.getAdapter(TypeToken.get(type));return new IResponseBodyConverter<>(gson, adapter); // 响应}@Overridepublic Converter<?, RequestBody> requestBodyConverter(Type type,Annotation[] parameterAnnotations, Annotation[] methodAnnotations,Retrofit retrofit) {System.out.println("#发起请求#");TypeAdapter<?> adapter = gson.getAdapter(TypeToken.get(type));return new IRequestBodyConverter<>(gson, adapter); // 请求}}
public class IRequestBodyConverter<T> implements Converter<T, RequestBody> {private static final MediaType MEDIA_TYPE = MediaType.parse("application/json; charset=UTF-8");static final Charset UTF_8 = Charset.forName("UTF-8");final Gson gson;final TypeAdapter<T> adapter;IRequestBodyConverter(Gson gson, TypeAdapter<T> adapter) {this.gson = gson;this.adapter = adapter;System.out.println("#IRequestBodyConverter初始化#");}@Overridepublic RequestBody convert(T value) throws IOException {String json = value.toString();System.out.println("#加密前#" + json);json = AesEncryptionUtil.encrypt(json);System.out.println("#加密后#" + json);return RequestBody.create(MEDIA_TYPE, json);}}
package factory;import java.io.IOException;import okhttp3.ResponseBody;import retrofit2.Converter;import com.google.gson.Gson;import com.google.gson.TypeAdapter;import com.wyhd.encry.decry.security.util.AesEncryptionUtil;public class IResponseBodyConverter<T> implements Converter<ResponseBody, T> {private final Gson gson;private final TypeAdapter<T> adapter;IResponseBodyConverter(Gson gson, TypeAdapter<T> adapter) {this.gson = gson;this.adapter = adapter;}@Overridepublic T convert(ResponseBody value) throws IOException {String string = value.string();System.out.println("#解密前#" + string);string = AesEncryptionUtil.decrypt(string);System.out.println("#解密后#" + string);return adapter.fromJson(string);}}

调用方法

public class RetrofitHelper {/** 基本路径 */public static final String BASE_URL = "https://api.imeizan.cn";public static void tst(String json) {json = AesEncryptionUtil.encrypt(json);Gson gson = new GsonBuilder().setLenient().create();Retrofit retrofit = new Retrofit.Builder().baseUrl(BASE_URL).client(getOkHttpClient()).addConverterFactory(IGsonFactory.create(gson)).build();IBannerService service = retrofit.create(IBannerService.class);Call<BannerResp> call = service.getBanner(json);call.enqueue(new Callback<BannerResp>() {@Overridepublic void onResponse(Call<BannerResp> call,Response<BannerResp> resp) {BannerResp body = resp.body();System.out.println("异步返回:" + body.toString());}@Overridepublic void onFailure(Call<BannerResp> msg, Throwable error) {System.out.println(msg.toString() + "|" + error.getMessage());}});final Call<BannerResp> clone = call.clone();new Thread() {public void run() {try {Response<BannerResp> execute = clone.execute();System.out.println("同步返回:" + execute.body().toString());} catch (Exception e) {System.out.println("同步返回:" + e.getMessage());}};}.start();}public static OkHttpClient getOkHttpClient() {// 日志显示级别HttpLoggingInterceptor.Level level = HttpLoggingInterceptor.Level.BODY;// 新建log拦截器HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() {@Overridepublic void log(String message) {System.out.println(message);}});loggingInterceptor.setLevel(level);// 定制OkHttpOkHttpClient.Builder httpClientBuilder = new OkHttpClient.Builder();// OkHttp进行添加拦截器loggingInterceptorhttpClientBuilder.addInterceptor(loggingInterceptor);return httpClientBuilder.build();}}
四:测试代码

public class MainActivity extends Activity {@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);BannerReq req = new BannerReq(1);Gson gson = new Gson();String json = gson.toJson(req);System.out.println(json);RetrofitHelper.tst(json);RetrofitHelper002.tst(json);}}

五:运行结果



原创粉丝点击