一、在build加入依赖
implementation 'com.squareup.okhttp3:okhttp:3.6.0'
implementation 'com.squareup.okio:okio:1.5.0'
implementation 'com.github.franmontiel:PersistentCookieJar:v1.0.1'
二、写网络请求工具类
import com.example.mowangtao.MVP.BaseApplication;
import com.franmontiel.persistentcookiejar.PersistentCookieJar;
import com.franmontiel.persistentcookiejar.cache.SetCookieCache;
import com.franmontiel.persistentcookiejar.persistence.SharedPrefsCookiePersistor;
import com.google.gson.Gson;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.concurrent.TimeUnit;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
public class RequestManager {
private OkHttpClient mOkHttpClient;
private static String BASE_URL = Constant.ServerletUrl;
private static RequestManager instance;
private Gson gson;
public RequestManager() {
PersistentCookieJar cookieJar = new PersistentCookieJar(new SetCookieCache(), new SharedPrefsCookiePersistor(BaseApplication.getInstance().getBaseContext()));
mOkHttpClient = new OkHttpClient.Builder()
.connectTimeout(10000, TimeUnit.MILLISECONDS)
.readTimeout(10000, TimeUnit.MILLISECONDS)
.cookieJar(cookieJar)
.build();
}
public static RequestManager getInstance() {
if (instance == null) {
synchronized (RequestManager.class) {
if (instance == null) {
instance = new RequestManager();
}
}
}
return instance;
}
/***
* post请求
*/
public void PostRequest(HashMap<String, Object> paramsMap, String url, final ResultCallback callback) throws UnsupportedEncodingException {
gson = new Gson();
String params = gson.toJson(paramsMap);
RequestBody body = RequestBody.create(MediaType.parse("application/json;charset=UTF-8"), params);
String requestUrl = BASE_URL + url;
final Request request = new Request.Builder()
.url(requestUrl)
.post(body)
.build();
Call callclient = mOkHttpClient.newCall(request);
callclient.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
callback.onError("网络请求失败,请稍后重试");
}
@Override
public void onResponse(Call call, final Response response) throws IOException {
if (response.isSuccessful()) {
int code = response.code();
if (code == 200) {//请求成功
String result = response.body().string();
callback.onResponse(String.valueOf(code), result);
} else
callback.onError(response.message());
} else {
callback.onError("网络请求失败,请稍后重试");
}
}
});
}
public interface ResultCallback {
void onResponse(String code, String response);
void onError(String msg);
}
}
三、在你需要判断是有获取到cookie地方使用
SharedPrefsCookiePersistor sharedPrefsCookiePersistor = new SharedPrefsCookiePersistor(StartActivity.this);
List<Cookie> cookies = sharedPrefsCookiePersistor.loadAll();