前言
在前幾篇中鲸沮,我們實現(xiàn)了基于MVP模式的Retrofit2+RXjava封裝搏色,今天要說的是使用Retrofit2和Okhttp 過程中遇到的一些問題
- 【Android架構(gòu)】基于MVP模式的Retrofit2+RXjava封裝(一)
- 【Android架構(gòu)】基于MVP模式的Retrofit2+RXjava封裝之文件下載(二)
- 【Android架構(gòu)】基于MVP模式的Retrofit2+RXjava封裝之文件上傳(三)
- 【Android架構(gòu)】基于MVP模式的Retrofit2+RXjava封裝之常見問題(四)
- 【Android架構(gòu)】基于MVP模式的Retrofit2+RXjava封裝之斷點下載(五)
- 【Android架構(gòu)】基于MVP模式的Retrofit2+RXjava封裝之數(shù)據(jù)預處理(六)
- 【Android架構(gòu)】基于MVP模式的Retrofit2+RXjava封裝之多Url(七)
- 【Android架構(gòu)】基于MVP模式的Retrofit2+RXjava封裝之Token的刷新(八)
問題
- 1.上傳數(shù)組
相信很多人都遇到到這個問題手报,這里說下筆者的2種方案:
方案一 把整個請求體轉(zhuǎn)換為JSON提交
首先是ApiServer
@POST("api/goods/send")
Observable<BaseModel> sendGoods(@Body RequestBody requestBody);
Presenter
String[] str = new String["123","234"];
HashMap<String, Object> map = new HashMap<>();
map.put("province", addressModel.getProvince());
map.put("city", addressModel.getCity());
map.put("area", addressModel.getArea());
map.put("zipcode", addressModel.getZipcode());
map.put("user_goods_ids", str);
RequestBody requestBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"),
new Gson().toJson(map));
mPresenter.sendGoods(requestBody);
方案二 模擬數(shù)組
首先是ApiServer
//商品評論(私有接口)
@POST("PrivateApi/goods/goodsComment")
@FormUrlEncoded
Observable<BaseModel> goodsComment(@FieldMap ArrayMap<String, Object> map);
Presenter
ArrayMap<String, Object> map = new ArrayMap<>();
map.put("goods_id", goods_id);
map.put("content", etElaluate.getText().toString().trim());
map.put("address", address);
for (int i = 0; i < data.size(); i++) {
map.put("img[" + i + "]", data.get(i));
}
presenter.goodsComment(map);
- 2.Cookie 持續(xù)化存儲
說道這里,不得不說挥转,Okhttp還是強大
client = new OkHttpClient.Builder()
.cookieJar(new CookiesManager(MyApplication.getContext()))
.connectTimeout(10, TimeUnit.SECONDS)
.readTimeout(10, TimeUnit.SECONDS)
// .sslSocketFactory()
.build();
創(chuàng)建OkHttpClient時兜看,可以傳遞一個實現(xiàn)了CookieJar 的自定義管理cookie類,只需要重寫其saveFromResponse(HttpUrl url, List<Cookie> cookies)和loadForRequest(HttpUrl url)方法撼嗓。
這2個方法的作用也很明顯柬采,一個是保存cookie欢唾,一個是獲取cookie
public class CookiesManager implements CookieJar {
private final PersistentCookieStore cookieStore;
public CookiesManager(Context context) {
cookieStore = new PersistentCookieStore(context);
}
@Override
public void saveFromResponse(HttpUrl url, List<Cookie> cookies) {
if (cookies.size() > 0) {
for (Cookie item : cookies) {
cookieStore.add(url, item);
}
}
}
@Override
public List<Cookie> loadForRequest(HttpUrl url) {
List<Cookie> cookies = cookieStore.get(url);
return cookies;
}
}
PersistentCookieStore
public class PersistentCookieStore {
private static final String LOG_TAG = "PersistentCookieStore";
public static final String COOKIE_PREFS = "Cookies_Prefs";
private final Map<String, ConcurrentHashMap<String, Cookie>> cookies;
private final SharedPreferences cookiePrefs;
public PersistentCookieStore(Context context) {
cookiePrefs = context.getSharedPreferences(COOKIE_PREFS, 0);
cookies = new ArrayMap<>();
//將持久化的cookies緩存到內(nèi)存中 即map cookies
Map<String, ?> prefsMap = cookiePrefs.getAll();
for (Map.Entry<String, ?> entry : prefsMap.entrySet()) {
String[] cookieNames = TextUtils.split((String) entry.getValue(), ",");
for (String name : cookieNames) {
String encodedCookie = cookiePrefs.getString(name, null);
if (encodedCookie != null) {
Cookie decodedCookie = decodeCookie(encodedCookie);
if (decodedCookie != null) {
if (!cookies.containsKey(entry.getKey())) {
cookies.put(entry.getKey(), new ConcurrentHashMap<String, Cookie>());
}
cookies.get(entry.getKey()).put(name, decodedCookie);
}
}
}
}
}
protected String getCookieToken(Cookie cookie) {
return cookie.name() + "@" + cookie.domain();
}
public void add(HttpUrl url, Cookie cookie) {
String name = getCookieToken(cookie);
//將cookies緩存到內(nèi)存中 如果緩存過期 就重置此cookie
if (!cookie.persistent()) {
if (!cookies.containsKey(url.host())) {
cookies.put(url.host(), new ConcurrentHashMap<String, Cookie>());
}
cookies.get(url.host()).put(name, cookie);
} else {
if (cookies.containsKey(url.host())) {
if (cookies.get(url.host()) != null) {
cookies.get(url.host()).remove(name);
}
}
}
if (cookies.get(url.host()) != null) {
//講cookies持久化到本地
SharedPreferences.Editor prefsWriter = cookiePrefs.edit();
prefsWriter.putString(url.host(), TextUtils.join(",", cookies.get(url.host()).keySet()));
prefsWriter.putString(name, encodeCookie(new SerializableOkHttpCookies(cookie)));
prefsWriter.apply();
}
}
public List<Cookie> get(HttpUrl url) {
ArrayList<Cookie> ret = new ArrayList<>();
if (cookies.containsKey(url.host()))
ret.addAll(cookies.get(url.host()).values());
return ret;
}
public boolean removeAll() {
SharedPreferences.Editor prefsWriter = cookiePrefs.edit();
prefsWriter.clear();
prefsWriter.apply();
cookies.clear();
return true;
}
public boolean remove(HttpUrl url, Cookie cookie) {
String name = getCookieToken(cookie);
if (cookies.containsKey(url.host()) && cookies.get(url.host()).containsKey(name)) {
cookies.get(url.host()).remove(name);
SharedPreferences.Editor prefsWriter = cookiePrefs.edit();
if (cookiePrefs.contains(name)) {
prefsWriter.remove(name);
}
prefsWriter.putString(url.host(), TextUtils.join(",", cookies.get(url.host()).keySet()));
prefsWriter.apply();
return true;
} else {
return false;
}
}
public List<Cookie> getCookies() {
ArrayList<Cookie> ret = new ArrayList<>();
for (String key : cookies.keySet())
ret.addAll(cookies.get(key).values());
return ret;
}
/**
* cookies 序列化成 string
*
* @param cookie 要序列化的cookie
* @return 序列化之后的string
*/
protected String encodeCookie(SerializableOkHttpCookies cookie) {
if (cookie == null)
return null;
ByteArrayOutputStream os = new ByteArrayOutputStream();
try {
ObjectOutputStream outputStream = new ObjectOutputStream(os);
outputStream.writeObject(cookie);
} catch (IOException e) {
Log.d(LOG_TAG, "IOException in encodeCookie", e);
return null;
}
return byteArrayToHexString(os.toByteArray());
}
/**
* 將字符串反序列化成cookies
*
* @param cookieString cookies string
* @return cookie object
*/
protected Cookie decodeCookie(String cookieString) {
byte[] bytes = hexStringToByteArray(cookieString);
ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes);
Cookie cookie = null;
try {
ObjectInputStream objectInputStream = new ObjectInputStream(byteArrayInputStream);
cookie = ((SerializableOkHttpCookies) objectInputStream.readObject()).getCookies();
} catch (IOException e) {
Log.d(LOG_TAG, "IOException in decodeCookie", e);
} catch (ClassNotFoundException e) {
Log.d(LOG_TAG, "ClassNotFoundException in decodeCookie", e);
}
return cookie;
}
/**
* 二進制數(shù)組轉(zhuǎn)十六進制字符串
*
* @param bytes byte array to be converted
* @return string containing hex values
*/
protected String byteArrayToHexString(byte[] bytes) {
StringBuilder sb = new StringBuilder(bytes.length * 2);
for (byte element : bytes) {
int v = element & 0xff;
if (v < 16) {
sb.append('0');
}
sb.append(Integer.toHexString(v));
}
return sb.toString().toUpperCase(Locale.US);
}
/**
* 十六進制字符串轉(zhuǎn)二進制數(shù)組
*
* @param hexString string of hex-encoded values
* @return decoded byte array
*/
protected byte[] hexStringToByteArray(String hexString) {
int len = hexString.length();
byte[] data = new byte[len / 2];
for (int i = 0; i < len; i += 2) {
data[i / 2] = (byte) ((Character.digit(hexString.charAt(i), 16) << 4) + Character.digit(hexString.charAt(i + 1), 16));
}
return data;
}
}
SerializableOkHttpCookies
public class SerializableOkHttpCookies implements Serializable {
private transient final Cookie cookies;
private transient Cookie clientCookies;
public SerializableOkHttpCookies(Cookie cookies) {
this.cookies = cookies;
}
public Cookie getCookies() {
Cookie bestCookies = cookies;
if (clientCookies != null) {
bestCookies = clientCookies;
}
return bestCookies;
}
private void writeObject(ObjectOutputStream out) throws IOException {
out.writeObject(cookies.name());
out.writeObject(cookies.value());
out.writeLong(cookies.expiresAt());
out.writeObject(cookies.domain());
out.writeObject(cookies.path());
out.writeBoolean(cookies.secure());
out.writeBoolean(cookies.httpOnly());
out.writeBoolean(cookies.hostOnly());
out.writeBoolean(cookies.persistent());
}
private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {
String name = (String) in.readObject();
String value = (String) in.readObject();
long expiresAt = in.readLong();
String domain = (String) in.readObject();
String path = (String) in.readObject();
boolean secure = in.readBoolean();
boolean httpOnly = in.readBoolean();
boolean hostOnly = in.readBoolean();
boolean persistent = in.readBoolean();
Cookie.Builder builder = new Cookie.Builder();
builder = builder.name(name);
builder = builder.value(value);
builder = builder.expiresAt(expiresAt);
builder = hostOnly ? builder.hostOnlyDomain(domain) : builder.domain(domain);
builder = builder.path(path);
builder = secure ? builder.secure() : builder;
builder = httpOnly ? builder.httpOnly() : builder;
clientCookies =builder.build();
}
}
此方法可供參考,也可以用其他方式實現(xiàn)粉捻,比如說ACache礁遣。
- 3.添加統(tǒng)一請求頭
跟cookie一樣,okhttp中已經(jīng)實現(xiàn)
在創(chuàng)建OkHttpClient時肩刃,可以添加自定義的攔截器
client = new OkHttpClient.Builder()
//添加log攔截器
.addInterceptor(headInterceptor)
.addInterceptor(interceptor)
.connectTimeout(10, TimeUnit.SECONDS)
.readTimeout(10, TimeUnit.SECONDS)
// .sslSocketFactory()
.build();
private Interceptor headInterceptor = new Interceptor() {
@Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
Request.Builder builder = request.newBuilder().addHeader("LEDAYOUXUAN", "159357456")
.addHeader("APP_TOKEN", UserImpl.getAppToken());
return chain.proceed(builder.build());
}
};
還有一種特別坑的情況祟霍,統(tǒng)一請求參數(shù)需要添加到請求body中
處理方式還是在攔截器中
HttpUrl httpUrl = request.url()
.newBuilder()
.addQueryParameter("login_token", token)
.build();
Request build = request.newBuilder()
.addHeader("clienttype", "1")
.addHeader("sdk_type", "android")
.addHeader("sdk_version_name", AppUtils.getVersionName(App.getContext()))
.addHeader("sdk_version", AppUtils.getVersionCode(App.getContext()) + "")
.addHeader("Cookie", UserImpl.getCookie())
.url(httpUrl)
.build();
這里會引申出一個問題,原生與h5混合開發(fā)時盈包,h5也需要cookie的處理沸呐,具體請點擊【Android Web】騰訊X5瀏覽器的集成與常見問題。
- 4.POST無參數(shù)
正常post 需要添加@FormUrlEncoded 注解呢燥,當post 無參時崭添,只需要去掉該注解即可。
@POST("PrivateApi/Users/verifySecond")
Observable<BaseModel> verifySecond();