Session 是保存在服务端,用于标识用户
Cookie 是保存在客户端的,浏览器端
Cookie使用HTTP Header 传递数据
Cookie机制定义了两种Header :Set-Cookie Header 和Cookie Header
Set-Cookie Header 包含于Web服务器的响应头(Response Header)中
Cookie Header 包含在浏览器客户端请求头(Reguest Header)中
绝大部分情况都是用 Cookie 来实现Session跟踪的 ,在 Cookie 里面记录了一个Session ID
Session ID 是一种机制,不同的环境有不同的叫法 比如: java web 是 JSESSIONID
常用:(1)自行获取 sessionId
HttpClient请求使用(一个例子)
classicApplication.getHeadersMap().put("JSESSIONID",sessionId);//01866fbe-725c-482b-aca1-dcd32a6dcfe2
HttpURLConnection请求使用
classicApplication.getHeadersMap().put("Cookie","SESSION="sessionId);//01866fbe-725c-482b-aca1-dcd32a6dcfe2
//参数名可以从取的sessionid中huode
String responseCookie = connection.getHeaderField("Set-Cookie");//取到所用的Cookie
if (responseCookie != null) {
//取出sessionId
String sessionId = responseCookie.substring(0, responseCookie.indexOf(";"));
Log.i(TAG, " responseCookie sessionId:" +sessionId);//responseCookie sessionId:SESSION=2aeeaf6b-f9f7-4106-a2ac-aa7038de388b
}
okhttp等使用
classicApplication.getHeadersMap().put("Cookie","SESSION="+sessionId);//01866fbe-725c-482b-aca1-dcd32a6dcfe2
(2)利用okhttp自带的方式1
// .addInterceptor(httpCookiesInterceptor)
public class HttpCookiesInterceptor implements Interceptor {
private List<String> mCookies=new ArrayList<>();
{
Log.i("zfq", "HttpCookiesInterceptor instance initializer: ");
}
@Override
public Response intercept(Chain chain) throws IOException {
//请求 设置Cookie
Request request = chain.request();
Request.Builder newBuilder = request.newBuilder();
//newBuilder.addHeader("Accept", "Application/JSON");
if (mCookies != null) {
for (String cookie : mCookies) {//1条
newBuilder.addHeader("Cookie", cookie);
Log.i("zfq", "HttpCookiesInterceptor intercept: Cookie:"+cookie);
}
}
Request newRequest = newBuilder.build();
//响应
Response response = chain.proceed(newRequest);
if (response.headers("Set-Cookie") != null){
for (String header : response.headers("Set-Cookie")) {//1条
mCookies.add(header);
Log.i("zfq", "HttpCookiesInterceptor intercept: Set-Cookie:"+header);
}
}
return response;
}
}
(2)利用okhttp自带的方式2
//.cookieJar(myCookieJar) //okhttp3
//OkHttp的是否单例影响着CookieJar的工作
CookieJar myCookieJar=new CookieJar() {
//private final
Map<String, List<Cookie>> cookiesMap= new HashMap<>();
{
Log.i("zfq", "OkHttpManager instance initializer: ");
}
@Override
public void saveFromResponse(HttpUrl url, List<Cookie> cookies) {
Log.i("zfq", "OkHttpManager saveFromResponse "+url);
cookiesMap.put(url.host(), cookies);
if (EmptyTool.isNotEmpty(cookies)) {
for (Cookie cookie : cookies) {
Log.i("zfq", "OkHttpManager saveFromResponse: " + cookie.value());
}
}
}
@Override
public List<Cookie> loadForRequest(HttpUrl url) {
Log.i("zfq", "OkHttpManager loadForRequest "+url);
List<Cookie> cookies = cookiesMap.get(url.host());
if (EmptyTool.isNotEmpty(cookies)) {
for (Cookie cookie : cookies) {
Log.i("zfq", "OkHttpManager saveFromResponse: " + cookie.value());
}
}
return cookies != null ? cookies : new ArrayList<Cookie>();
}
};