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

我还在拥抱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;
	}


	@Override
	public 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;

		@Override
		public String toString() {
			return "Banner [id=" + id + ", name=" + name + "]";
		}

	}

	@Override
	public 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;
	}

	@Override
	public Converter<ResponseBody, ?> responseBodyConverter(Type type,
			Annotation[] annotations, Retrofit retrofit) {
		TypeAdapter<?> adapter = gson.getAdapter(TypeToken.get(type));
		return new IResponseBodyConverter<>(gson, adapter); // 响应
	}

	@Override
	public 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初始化#");
	}

	@Override
	public 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;
	}

	@Override
	public 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>() {

			@Override
			public void onResponse(Call<BannerResp> call,
					Response<BannerResp> resp) {
				BannerResp body = resp.body();
				System.out.println("异步返回:" + body.toString());
			}

			@Override
			public 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() {
					@Override
					public void log(String message) {
						System.out.println(message);
					}
				});
		loggingInterceptor.setLevel(level);
		// 定制OkHttp
		OkHttpClient.Builder httpClientBuilder = new OkHttpClient.Builder();
		// OkHttp进行添加拦截器loggingInterceptor
		httpClientBuilder.addInterceptor(loggingInterceptor);
		return httpClientBuilder.build();
	}
}
四:测试代码

public class MainActivity extends Activity {

	@Override
	protected 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);
	}

}

五:运行结果



评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值