Retrofit2封裝之路(請求引數加密解密)(一)
阿新 • • 發佈:2019-02-09
我還在擁抱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);
}
}
五:執行結果